// JavaScript Document

/*
	1.01.01
	13/01/2011 - Desarrollado por <Odd One Out> - www.OddOneOut.info
	
	o3_ajax
	o3_atributo
	o3_etiqueta
	o3_title
	o3_opacity
	o3_fade
	o3_email
	o3_enter
	o3_cancelar_bubble
	o3_first_child
	o3_last_child
	o3_nodo_anterior
	o3_nodo_siguiente
	o3_eliminar
	o3_desplegar
	o3_cortina
	o3_centrar
	o3_urlencode
	o3_urldecode
	o3_precargar
	o3_get_flash_movie
	o3_addEventListener
	o3_removeEventListener
	
	ATAJOS
	o3_mostrar
	o3_ocultar
*/

var mouse_x;
var mouse_y;

var o3_imagenes_precargadas = [];

var o3_eventListener = [];

// Se utiliza para llamar un documento con el metodo AJAX. El texto que devuelva dicho documento se ejecutara en lenguaje JavaScript mediante la funcion eval().
function o3_ajax(url, cache)
{
	var datos = url.split("?");
	var url = datos[0];
	var datos = datos[1];
	if (window.XMLHttpRequest)
	{
		// code for IE7+, Firefox, Chrome, Opera, Safari
		var ajax = new XMLHttpRequest();
	}
	else
	{
		// code for IE6, IE5
		var ajax = new ActiveXObject("Microsoft.XMLHTTP");
	}
	ajax.onreadystatechange = function()
	{
		if (ajax.readyState == 4 && ajax.status == 200)
		{
			eval(ajax.responseText);
		}
	}
	if (!cache)
	{
		var fecha = new Date()
		var codigo_peticion = fecha.getTime();
		if (datos == undefined)
		{
			datos = '?codigo_peticion=' + codigo_peticion;
		}
		else
		{
			datos += '&codigo_peticion=' + codigo_peticion;
		}
	}
	ajax.open("POST", url, true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.send(datos);
}

// Busca un atributo y devuelve su valor en caso de existir
function o3_atributo(atributo, configuracion)
{
	configuracion = ';' + configuracion;
	atributo = ';' + atributo + '=';
	if (configuracion.search(atributo) != -1)
	{
		var posicion_atributo = configuracion.indexOf(atributo);
		var configuracion = configuracion.substr(posicion_atributo + atributo.length)
		var posicion_siguiente_atributo = configuracion.indexOf(';');
		if (posicion_siguiente_atributo != -1)
		{
			configuracion = configuracion.substr(0, posicion_siguiente_atributo);
		}
		return configuracion;
	}
	else
	{
		return '';
	}
}

// Agrega una etiqueta a un campo de texto la cual se quita al escribir en el mismo y vuelve a aparecer si se quita todo el texto
// Atributos: etiqueta, color.

var valor_etiqueta;
function o3_etiqueta(objeto, atributos)
{
	var accion = o3_atributo('accion', atributos);
	var etiqueta = o3_atributo('etiqueta', atributos);
	if (o3_atributo('color', atributos) != '')
	{
		var color = o3_atributo('color', atributos);
	}
	else
	{
		var color = '#000';
	}
	if (accion == '')
	{
		document.getElementById(objeto).onfocus = Function("o3_etiqueta('" + objeto + "', '" + atributos + ";accion=focus');");
		document.getElementById(objeto).onblur = Function("o3_etiqueta('" + objeto + "', '" + atributos + ";accion=blur');");
		document.getElementById(objeto).onkeyup = Function("o3_etiqueta('" + objeto + "', '" + atributos + ";accion=keydown');");
		document.getElementById(objeto).style.color = '#999';
		document.getElementById(objeto).style.fontStyle = 'italic';
		document.getElementById(objeto).value = etiqueta;
	}
	else if (accion == 'focus')
	{
		valor_etiqueta = document.getElementById(objeto).value;
		document.getElementById(objeto).select();
	}
	else if (accion == 'blur')
	{
		if (document.getElementById(objeto).value == '')
		{
			document.getElementById(objeto).style.color = '#999';
			document.getElementById(objeto).style.fontStyle = 'italic';
			document.getElementById(objeto).value = etiqueta;
		}
	}
	else if (accion == 'keydown')
	{
		var nuevo_valor = document.getElementById(objeto).value;
		if (valor_etiqueta != nuevo_valor)
		{
			document.getElementById(objeto).style.color = color;
			document.getElementById(objeto).style.fontStyle = 'normal';
		}
	}
}

// Desplega una ventana con texto y atributos sobre el objeto seleccionado.
// Atributos: background-color, border, padding, color, font-family, font-size, z-index, text-align, contenido, width, max-width, opacity, distancia-puntero, fade.
function o3_title(objeto, contenido, atributos)
{
	document.onmousemove = obtener_coordenadas;
	
	function obtener_coordenadas(evento)
	{
		evento = evento || window.event;
		mouse_x = evento.clientX;
		mouse_y = evento.clientY;
	}
	
	var accion = o3_atributo('accion', atributos);
	if (accion == '')
	{
		document.getElementById(objeto).onmouseover = Function("o3_title('" + objeto + "', '" + contenido + "', '" + atributos + ";accion=mover');");
		document.getElementById(objeto).onmousemove = Function("o3_title('" + objeto + "', '" + contenido + "', '" + atributos + ";accion=mover');");
		document.getElementById(objeto).onmouseout = Function("o3_title('" + objeto + "', '" + contenido + "', '" + atributos + ";accion=quitar');");
	}
	else if (accion == 'mover')
	{
		if (!document.getElementById('div_title'))
		{
			var div_title = document.createElement('div');
			div_title.id = 'div_title';
			div_title.style.position = 'fixed';
			div_title.style.backgroundColor = o3_atributo('background-color', atributos) ? o3_atributo('background-color', atributos) : '#000';
			div_title.style.border = o3_atributo('border', atributos) ? o3_atributo('border', atributos) : '1px solid #FFF';
			div_title.style.padding = o3_atributo('padding', atributos) ? o3_atributo('padding', atributos) : '5px';
			div_title.style.color = o3_atributo('color', atributos) ? o3_atributo('color', atributos) : '#FFF';
			div_title.style.fontFamily = o3_atributo('font-family', atributos) ? o3_atributo('font-family', atributos) : 'Verdana, Geneva, sans-serif';
			div_title.style.fontSize = o3_atributo('font-size', atributos) ? o3_atributo('font-size', atributos) : '10px';
			div_title.style.zIndex = o3_atributo('z-index', atributos) ? o3_atributo('z-index', atributos) : '99';
			div_title.style.textAlign = o3_atributo('text-align', atributos) ? o3_atributo('text-align', atributos) : 'left';
			div_title.innerHTML = contenido;
			document.body.appendChild(div_title);

			if (o3_atributo('width', atributos) != '')
			{
				document.getElementById('div_title').style.width = parseInt(o3_atributo('width', atributos)) + 'px';
			}
			
			if (o3_atributo('max-width', atributos) != '')
			{
				document.getElementById('div_title').style.maxWidth = parseInt(o3_atributo('max-width', atributos)) + 'px';
			}

			o3_opacity('div_title', 0);
			if (o3_atributo('opacity', atributos) != '')
			{
				if (o3_atributo('fade', atributos) == true)
				{
					o3_fade('div_title', o3_atributo('opacity', atributos), 250)
				}
				else
				{
					o3_opacity('div_title', o3_atributo('opacity', atributos));
				}
			}
			else
			{
				if (o3_atributo('fade', atributos) == true)
				{
					o3_fade('div_title', 70, 250)
				}
				else
				{
					o3_opacity('div_title', 70);
				}
			}
		}
		
		var ancho_ventana = document.documentElement.clientWidth;
		var alto_ventana = document.documentElement.clientHeight;
		var ancho_title = document.getElementById('div_title').clientWidth;
		var alto_title = document.getElementById('div_title').clientHeight;
		
		if (o3_atributo('distancia-puntero', atributos) != '')
		{
			var distancia_puntero = parseInt(o3_atributo('distancia-puntero', atributos));
		}
		else
		{
			var distancia_puntero = 20;
		}

		if ((mouse_x + ancho_title + distancia_puntero) < ancho_ventana)
		{
			document.getElementById('div_title').style.left = (mouse_x + distancia_puntero) + 'px';
		}
		else
		{
			document.getElementById('div_title').style.left = (mouse_x - distancia_puntero - ancho_title) + 'px';
		}
		if ((mouse_y + alto_title + distancia_puntero) < alto_ventana)
		{
			document.getElementById('div_title').style.top = (mouse_y + distancia_puntero) + 'px';
		}
		else
		{
			if (mouse_y - distancia_puntero - alto_title >= 0)
			{
				document.getElementById('div_title').style.top = (mouse_y - distancia_puntero - alto_title) + 'px';
			}
			else
			{
				document.getElementById('div_title').style.top = '0px';
			}
		}
	}
	else if (accion == 'quitar')
	{
		if (document.getElementById('div_title'))
		{
			document.body.removeChild(document.getElementById('div_title'));
		}
	}
}

// Cambia la opacidad de un objeto.
function o3_opacity(objeto, opacidad)
{
	if (document.getElementById(objeto))
	{
		document.getElementById(objeto).style.opacity = opacidad / 100;
		document.getElementById(objeto).style.filter = 'alpha(opacity = ' + opacidad + ')';
	}
}

// Cambia gradualmente la opacidad de un objeto.
function o3_fade(objeto, porcentaje, milisegundos)
{
	var intervalos = milisegundos / 50;
	for (i = 0; i < intervalos; i++)
	{
		var opacidad_inicial = document.getElementById(objeto).style.opacity * 100;
		var nueva_opacidad = opacidad_inicial - ((opacidad_inicial - porcentaje) / intervalos) * (i + 1);
		setTimeout("o3_opacity('" + objeto + "', " + nueva_opacidad + ");", i * milisegundos / intervalos);
	}
}

// Verifica si el e-mail ingresado es valido.
function o3_email(email)
{
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return filter.test(email)? true: false;
}

// Si la tecla presionada es ENTER ejecuta el string ingresado como una funcion.
function o3_enter(funcion, event)
{
	if (event.keyCode == 13) eval(funcion);
}

// Cancela el efecto bubble que produce la expansion del evento a los niveles superiores.
function o3_cancelar_bubble(event)
{
	if (event.stopPropagation) event.stopPropagation(); else window.event.cancelBubble = true;
}

// Devuelve el elemento firstChild del objeto seleccionado.
function o3_first_child(objeto)
{
	var first_child = document.getElementById(objeto).firstChild;
	while (first_child.nodeType != 1)
	{
		first_child = first_child.nextSibling;
		if (first_child == null)
		{
			return '';
			break;
		}
	}
	return first_child;
}

// Devuelve el elemento lastChild del objeto seleccionado.
function o3_last_child(objeto)
{
	var last_child = document.getElementById(objeto).lastChild;
	while (last_child.nodeType != 1)
	{
		last_child = last_child.previousSibling;
		if (last_child == null)
		{
			return '';
			break;
		}
	}
	return last_child;
}

// Devuelve el nodo anterior al objeto seleccionado.
function o3_nodo_anterior(objeto)
{
	var nodo_anterior = document.getElementById(objeto).previousSibling;
	if (nodo_anterior != null)
	{
		while (nodo_anterior.nodeType != 1)
		{
			nodo_anterior = nodo_anterior.previousSibling;
			if (nodo_anterior == null)
			{
				return '';
				break;
			}
		}
		return nodo_anterior;
	}
	else
	{
		return '';
	}
}

// Devuelve el nodo siguiente al objeto seleccionado.
function o3_nodo_siguiente(objeto)
{
	var nodo_siguiente = document.getElementById(objeto).nextSibling;
	if (nodo_siguiente != null)
	{
		while (nodo_siguiente.nodeType != 1)
		{
			nodo_siguiente = nodo_siguiente.nextSibling;
			if (nodo_siguiente == null)
			{
				return '';
				break;
			}
		}
		return nodo_siguiente;
	}
	else
	{
		return '';
	}
}

// Elimina el nodo seleccionado.
function o3_eliminar(objeto)
{
	document.getElementById(objeto).parentNode.removeChild(document.getElementById(objeto));
}

// Desplega o contrae un elemento desde 0 hasta su tamaņo original.
function o3_desplegar(objeto, eje, duracion)
{
	document.getElementById(objeto).style.overflow = 'hidden';
	if (document.getElementById(objeto).border != undefined) var borde = parseInt(document.getElementById(objeto).style.borderWidth) * 2; else var borde = 0;
	if (document.getElementById(objeto).style.display == 'none')
	{
		var position = document.getElementById(objeto).style.position;
		var opacity = document.getElementById(objeto).style.opacity * 100;
		o3_opacity(objeto, 0);
		document.getElementById(objeto).style.position = 'fixed';
		document.getElementById(objeto).style.display = 'block';
		var ancho = document.getElementById(objeto).offsetWidth - borde;
		var alto = document.getElementById(objeto).offsetHeight - borde;
		document.getElementById(objeto).style.position = position;
		document.getElementById(objeto).style.display = 'none';
		o3_opacity(objeto, opacity);

		if (eje != 'y')
		{
			document.getElementById(objeto).style.width = '0px';
		}
		if (eje != 'x')
		{
			document.getElementById(objeto).style.height = '0px';
		}
		document.getElementById(objeto).style.display = 'block';
		
		if (eje != 'y')
		{
			for (i = 1; i <= duracion * 0.02; i++)
			{
				var intervalo = ancho / (duracion * 0.02) * i;
				setTimeout("document.getElementById('" + objeto + "').style.width = '" + intervalo + "px';", 50 * i);
			}
		}
		if (eje != 'x')
		{
			for (i = 1; i <= duracion * 0.02; i++)
			{
				var intervalo = alto / (duracion * 0.02) * i;
				setTimeout("document.getElementById('" + objeto + "').style.height = '" + intervalo + "px';", 50 * i);
			}
		}
		setTimeout("document.getElementById('" + objeto + "').style.width = '';", duracion);
		setTimeout("document.getElementById('" + objeto + "').style.height = '';", duracion);
	}
	else
	{
		var ancho = document.getElementById(objeto).offsetWidth - borde;
		var alto = document.getElementById(objeto).offsetHeight - borde;

		if (eje != 'y')
		{
			for (i = 1; i <= duracion * 0.02; i++)
			{
				var intervalo = ancho - ancho / (duracion * 0.02) * i;
				setTimeout("document.getElementById('" + objeto + "').style.width = '" + intervalo + "px';", 50 * i);
			}
		}
		if (eje != 'x')
		{
			for (i = 1; i <= duracion * 0.02; i++)
			{
				var intervalo = alto - alto / (duracion * 0.02) * i;
				setTimeout("document.getElementById('" + objeto + "').style.height = '" + intervalo + "px';", 50 * i);
			}
		}
		setTimeout("document.getElementById('" + objeto + "').style.display = 'none';", duracion);
		setTimeout("document.getElementById('" + objeto + "').style.width = '';", duracion);
		setTimeout("document.getElementById('" + objeto + "').style.height = '';", duracion);
	}
}

// Crea una cortina translucida con el id "div_cortina_temporal"
// Atributos: color, opacity, z-index, fade, duracion
function o3_cortina(atributos)
{
	var ancho_ventana = document.documentElement.clientWidth;
	var alto_ventana = document.documentElement.clientHeight;

	var cortina = document.createElement('div');
	cortina.id = 'div_cortina_temporal';
	cortina.style.left = '0px';
	cortina.style.top = '0px';
	cortina.style.width = ancho_ventana + 'px';
	cortina.style.height = alto_ventana + 'px';
	cortina.style.position = 'fixed';
	var backgroundcolor = o3_atributo('color', atributos);
	if (backgroundcolor == '') backgroundcolor = '#000';
	cortina.style.backgroundColor = backgroundcolor;
	var zindex = o3_atributo('z-index', atributos);
	if (zindex == '') zindex = 90;
	cortina.style.zIndex = zindex;
	if (o3_atributo('fade', atributos) == 'true')
	{
		cortina.style.display = 'none';
		document.body.appendChild(cortina);
		o3_opacity('div_cortina_temporal', 0);
		cortina.style.display = 'block';
		var backgroundopacity = o3_atributo('opacity', atributos);
		if (backgroundopacity == '') backgroundopacity = 80;
		var duracion = o3_atributo('duracion', atributos);
		if (duracion == '') duracion = 500;
		o3_fade('div_cortina_temporal', backgroundopacity, duracion);
	}
	else
	{
		document.body.appendChild(cortina);
		var backgroundopacity = o3_atributo('opacity', atributos);
		if (backgroundopacity == '') backgroundopacity = 80;
		o3_opacity('div_cortina_temporal', backgroundopacity);
	}
}

// Centra un objeto
function o3_centrar(objeto)
{
	if (document.getElementById(objeto).style.display == 'none') var visible = false; else var visible = true;
	document.getElementById(objeto).style.display = 'block';
	var ancho = document.getElementById(objeto).offsetWidth;
	var alto = document.getElementById(objeto).offsetHeight;
	if (!visible) document.getElementById(objeto).style.display = 'none';
	
	var ancho_ventana = document.documentElement.clientWidth;
	var alto_ventana = document.documentElement.clientHeight;
	
	document.getElementById(objeto).style.left = (ancho_ventana - ancho) / 2 + 'px';
	document.getElementById(objeto).style.top = (alto_ventana - alto) / 2 + 'px';
}

// Codifica un String del mismo modo que lo hace la funcion rawurlencode de PHP
function o3_urlencode(string)
{
	string = encodeURIComponent(string.replace(/\n/g, '<br />').replace(/\r/g, ''));
	string = string.replace(/\%20/g, '+');
	string = string.replace(/\*/g, '%2A');
	string = string.replace(/\!/g, '%21');
	string = string.replace(/\'/g, '%27');
	string = string.replace(/\(/g, '%28');
	string = string.replace(/\)/g, '%29');
	string = string.replace(/\~/g, '%7E');
	return string;
}

// Decodifica un String del mismo modo que lo hace la funcion rawurldecode de PHP
function o3_urldecode(string)
{
	string = string.replace(/%7E/g, '\~');
	string = string.replace(/%29/g, '\)');
	string = string.replace(/%28/g, '\(');
	string = string.replace(/%27/g, '\'');
	string = string.replace(/%21/g, '\!');
	string = string.replace(/%2A/g, '\*');
	string = string.replace(/\+/g, '%20');
	string = decodeURIComponent(string).replace(/<br \/>/g, '\n');
	return string;
}

// Precarga una imagen para mostrarla sin esperas en el futuro
function o3_precargar(imagen)
{
	var id_imagen = o3_imagenes_precargadas.length;
	o3_imagenes_precargadas[id_imagen] = new Image();
	o3_imagenes_precargadas[id_imagen].src = imagen;
	return id_imagen;
}

// Permite acceder a una pelicula de Flash
function o3_get_flash_movie(movie)
{
	if (navigator.appName.indexOf("Microsoft") != -1)
	{
		return window[movie];
	}
	else
	{
		if (navigator.appVersion.indexOf("Safari") != -1 || navigator.appVersion.indexOf("Chrome") != -1)
		{
			return document.all[movie];
		}
		else
		{
			return document[movie];
		}
	}
}

// Agrega un eventListener al objeto. Ejemplo: o3_addEventListener(document.getElementById('id'), 'click', funcion[, argumento_1][, argumento_1]);
// El eventListener queda almacenado en el array o3_eventListener
function o3_addEventListener(elemento, tipo, funcion)
{
	var argumentos = [];
	var string_funcion = 'funcion(e);';
	if (arguments[3])
	{
		string_funcion = 'funcion(e';
		for (i = 3; i < arguments.length; i++)
		{
			if (typeof(arguments[i]) == 'string')
			{
				string_funcion += ', "' + arguments[i] + '"';
			}
			else
			{
				string_funcion += ', ' + arguments[i];
			}
		}
		string_funcion += ');';
	}
	if (document.addEventListener)
	{
		o3_eventListener.push(function(e){eval(string_funcion);});
		elemento.addEventListener(tipo, o3_eventListener[o3_eventListener.length - 1], false);
	}
	else
	{
		o3_eventListener.push(function(e){eval(string_funcion);});
		elemento.attachEvent("on" + tipo, o3_eventListener[o3_eventListener.length - 1]);
	}
}

// Remueve un eventListener de un objeto. Ejemplo: o3_removeEventListener(document.getElementById('id'), 'click', o3_eventListener[0]);
// Recuerde que los eventos agregados quedan almacenados en el array o3_eventListener
function o3_removeEventListener(elemento, tipo, funcion)
{
	var string_funcion = 'funcion(e);';
	if (document.addEventListener)
	{
		elemento.removeEventListener(tipo, funcion, false);
	}
	else
	{
		elemento.detachEvent("on" + tipo, funcion);
	}
}



// ATAJOS

// diplay = 'block'
function o3_mostrar(id)
{
	document.getElementById(id).style.display = 'block';
}

// diplay = 'none'
function o3_ocultar(id)
{
	document.getElementById(id).style.display = 'none';
}
