	var orden = "";
	var primera = 1;
	var tiempo = 0;
	var max_tiempo = 2500000;
	
	function actRanking(ind) {
		sndReqInd(ind);
		if((ind == 'IB') || (ind == '5E')) {
			sndReqRat(ind);
			sndReqTec(ind);
		}
	}
	
	function actVotos(codigo,voto) {
		if (typeof(votos) != 'undefined') {
		votos[codigo] = typeof(votos[codigo]) != 'undefined' ? votos[codigo] + voto : voto;
		valores = document.body.getElementsByTagName("SPAN");
		for(i=0;i<valores.length;i++) {
			if(valores[i].id.indexOf('votos-' + codigo) == 0) {
				valores[i].innerHTML = votos[codigo] + ' votos';
			}
		}
		}
	}

	function createRequestObject() {
		var ro;
		var browser = navigator.appName;
		if(browser == "Microsoft Internet Explorer") {
			ro = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else {
					ro = new XMLHttpRequest();
		}
    	return ro;
	}

	var valoresInd = new Array();
	var valoresRat = new Array();
	var valoresTec = new Array();
	var elemento = 'indice';
	var indice = '';
	var prueba = 0;

	function sndReqInd(ind) {
		var http = createRequestObject();
		indice = ind;
		http.open('get', '/backend/indices_txt.php?indice=' + ind + '&r=' + Math.random());
		http.onreadystatechange = function handleResponse() {
			if((http.readyState == 4) && (http.status == 200)) {
				valoresInd = new Array();
				
				var response = http.responseText;

				campos = response.split("#");
				for (i = 1; i < campos.length; i++) {
					campos2 = campos[i].split("=");
					eval(campos2[0] + ' = campos2[1].split("|")');
				}
				
				for (i = 0; i < valor.length - 2; i++) {
					valoresInd[i] = new valInd(valor[i], precios[i], aperturas[i], maximos[i], minimos[i], anteriores[i], variaciones[i], variaciones_por[i], volumenes[i], volumenes_ver[i], horas[i], horas_ver[i], codigos[i]);
				}

				mostrar_tabla_ar('variacion_por','max',valoresInd);
				mostrar_tabla_ar('variacion_por','min',valoresInd);
				mostrar_tabla_ar('volumen','max',valoresInd);
				mostrar_tabla_ar('volumen','min',valoresInd);
			}
		}
		http.send(null);
		
		tiempo = ((tiempo + 500000) > max_tiempo) ? max_tiempo : (tiempo + 500000);
		
		// setTimeout("sndReq('"+ind+"')", tiempo);
	}

	function sndReqIndRecomendaciones(ind) {
		var http = createRequestObject();
		indice = ind;
		http.open('get', '/backend/indices_txt.php?indice=' + ind + '&r=' + Math.random());
		http.onreadystatechange = function handleResponse() {
			if((http.readyState == 4) && (http.status == 200)) {
				//valoresInd = new Array();
				
				var response = http.responseText;

				campos = response.split("#");
				for (i = 1; i < campos.length; i++) {
					campos2 = campos[i].split("=");
					eval(campos2[0] + ' = campos2[1].split("|")');
				}
				
				for (i = 0; i < valor.length - 2; i++) {
					valoresInd[i] = new valInd(valor[i], precios[i], aperturas[i], maximos[i], minimos[i], anteriores[i], variaciones[i], variaciones_por[i], volumenes[i], volumenes_ver[i], horas[i], horas_ver[i], codigos[i]);
				}

				mostrar_tabla_ar_recomendaciones('variacion_por','max',valoresInd);

			}
		}
		http.send(null);
		
		tiempo = ((tiempo + 500000) > max_tiempo) ? max_tiempo : (tiempo + 500000);
		
		// setTimeout("sndReq('"+ind+"')", tiempo);
	}

	function sndReqRat(ind) {
		var http = createRequestObject();
		indice = ind;
		http.open('get', '/backend/indices_ratios.php?indice=' + ind + '&r=' + Math.random());
		http.onreadystatechange = function handleResponse() {
			if((http.readyState == 4) && (http.status == 200)) {
				valoresRat = new Array();
				
				var response = http.responseText;

				campos = response.split("#");
				for (i = 1; i < campos.length; i++) {
					campos2 = campos[i].split("=");
					eval(campos2[0] + ' = campos2[1].split("|")');
				}
				
				for (i = 0; i < valor.length - 2; i++) {
					valoresRat[i] = new valRat(valor[i], precios[i], pers[i], bpas[i], rentxdivs[i], prvalores[i], payouts[i], betas[i], alfas[i], corranuales[i], volatanuales[i], codigo_valores[i], codigo_mercados[i], variaciones_por[i]);
				}

				mostrar_tabla_ar('per','max',valoresRat);
				mostrar_tabla_ar('per','min',valoresRat);
				mostrar_tabla_ar('bpa','max',valoresRat);
				mostrar_tabla_ar('bpa','min',valoresRat);
			}
		}
		http.send(null);
		
		tiempo = ((tiempo + 500000) > max_tiempo) ? max_tiempo : (tiempo + 500000);
		
		// setTimeout("sndReq('"+ind+"')", tiempo);
	}

	function sndReqTec(ind) {
		var http = createRequestObject();
		indice = ind;
		http.open('get', '/backend/indices_tecnico.php?indice=' + ind + '&r=' + Math.random());
		http.onreadystatechange = function handleResponse() {
			if((http.readyState == 4) && (http.status == 200)) {
				valoresTec = new Array();
				
				var response = http.responseText;

				campos = response.split("#");
				for (i = 1; i < campos.length; i++) {
					campos2 = campos[i].split("=");
					eval(campos2[0] + ' = campos2[1].split("|")');
				}
				
				for(i = 0; i < valor.length - 2; i++) {
					valoresTec[i] = new valTec(valor[i], precios[i], soportes[i], resistencias[i], codigo_valores[i], codigo_mercados[i], variaciones_por[i]);

				}

				mostrar_tabla_ar('soporte_por','min',valoresTec);
				mostrar_tabla_ar('resistencia_por','min',valoresTec);
			}
		}
		http.send(null);

		tiempo = ((tiempo + 500000) > max_tiempo) ? max_tiempo : (tiempo + 500000);
		
		// setTimeout("sndReq('"+ind+"')", tiempo);
	}


	function sndReqVot(mercado,valor,voto,actualizar) {
		if(actualizar == null) actualizar = 1;
		
		var docTitle = document.title;
		var arrayTitle = docTitle.split(' | ');
		
		var http = createRequestObject();
		http.open('get', '/backend/cotizaciones/votos.php?mercado=' + mercado + '&valor=' + valor + '&voto=' + voto + '&actualizar=' + actualizar + '&r=' + Math.random() + '&titulo=' + arrayTitle[0] + '&url=' + document.location.href);
		http.onreadystatechange = function handleResponse() {
			if((http.readyState == 4) && (http.status == 200)) {
				var response = http.responseText;
				eval(response);
			}
		}
		http.send(null);
	}

	/* function httpVTo(ind) {
		indice = ind;
		httpVTo.open('get', '/mercados/votos_totales.php?indice=' + ind);
		httpVTo.onreadystatechange = handleResponseVTo;
		httpVTo.send(null);
	} */
	
	function mostrar_tabla_ar(tipo,orden,valoresArray) {
		var valores = valoresArray;
		elemento = tipo;
		
		sufijo_orden = orden == 'min' ? '' : '_r';
		
		eval('valores.sort(ordenar_numero' + sufijo_orden + ')');
		j = 1;
		i = 0;
		while((j < 6) && (i<valores.length)) {
			eval('dato3 = valores[i].' + tipo);
			if(dato3 == '') {
				i++;
				continue;
			}

			
			codigo_valormercado = typeof(valores[i].codigo_mercado) != 'undefined' ? valores[i].codigo_mercado + '_' + valores[i].codigo_valor : valores[i].codigo_valor;
			//alert (codigo_valormercado);
			codigos = codigo_valormercado.split('_');
			codigo_mercado = codigos[0];
			codigo_valor = codigos[1];

			// Enlace al Indice
			enlace1 = valores[i].indice;
			enlace1 = enlace1.replace(/ /g,"-");
			enlace1 = enlace1.replace(/''/g,"__");

			if (codigo_mercado == 'M'){
				enlace2 = enlace1 + '-mercadocontinuo.htm';
			}else if (codigo_mercado == 'NE'){
				enlace2 = enlace1 + '-mercadocontinuo.htm';
			}else if (codigo_mercado == 'MI'){
				enlace2 = enlace1 + '-milan.htm';
			}else if (codigo_mercado == 'BR'){
				enlace2 = enlace1 + '-bruselas.htm';
			}else if (codigo_mercado == 'XT'){
				enlace2 = enlace1 + '-frankfurt.htm';
			}else if (codigo_mercado == 'PA'){
				enlace2 = enlace1 + '-paris.htm';
			}else if (codigo_mercado == 'AM'){
				enlace2 = enlace1 + '-amsterdam.htm';
			}else if (codigo_mercado == 'NQ'){
				enlace2 = enlace1 + '-nasdaq.htm';
			}else if (codigo_mercado == 'NY'){
				enlace2 = enlace1 + '-dow-jones.htm';
			}else if (codigo_mercado == 'SV'){
				enlace2 = enlace1 + '-mercadoalternativo.htm';
			}else if (codigo_mercado == 'I'){
				enlace2 = enlace1.toLowerCase() + '.htm';
			}else{
				enlace2 = enlace1 + '.htm';
			}
			num_votos = typeof(votos[codigo_valormercado]) != 'undefined' ? votos[codigo_valormercado] : 0;

			// Bocadillo de Indice
			id_indice = tipo + '-' + orden + '-' + j + '-indice';
			indice = '<div class="rankingmas" onclick="document.getElementById(\'' + id_indice + '\').style.display = \'block\';">';
			indice += '<div class="leyenda" id="' + id_indice + '" onmouseover="document.getElementById(\'' + id_indice + '\').style.display = \'block\';" onmouseout="document.getElementById(\'' + id_indice + '\').style.display = \'none\';">';
			indice += '<div class="ico"><img src="/img/ranking_esquina_leyenda.gif" alt="" /></div>';
			indice += '<h2><a href="/cotizacion/' + enlace2 + '" class="valor">' + valores[i].indice + '</a></h2>';
			indice += '<div class="enlaces"><p><a href="javascript:annadirFav(\'' + codigo_valor + '\');">[+] añadir a favoritos</a></p><p><a href="/include/comprar.php?mercado=' + codigo_valor + '">[+] añadir a mi cartera</a></p></div>';
			indice += '<div class="votavalor">VOTA ESTE VALOR</div>';
			indice += '<div class="valoracion">';
			indice += '<a href="JavaScript:sndReqVot(\'' + codigo_mercado + '\',\'' + codigo_valor + '\',\'1\')" class="votamas"><img src="/img/ranking_votamas.gif" alt="Vota más" /></a> <a href="JavaScript:sndReqVot(\'' + codigo_mercado + '\',\'' + codigo_valor + '\',\'-1\')" class="votamenos"><img src="/img/ranking_votamenos.gif" alt="Vota menos" /></a> <span id="votos-' + codigo_valormercado + '-' + tipo + '-' + orden + '-' + j + '">' + num_votos + ' votos</span>';
			indice += '<div class="clear"></div>';
			indice += '</div>';
			indice += '</div>';
			indice += '<img src="/img/ranking_leyendamas.gif" alt="" />';
			indice += '</div>';
			indice += '<a href="/cotizacion/' + enlace2 + '" class="valor">' + valores[i].indice + '</a>';
			
			
			window.document.getElementById(tipo + '-' + orden + '-' + j + '-1').innerHTML = indice;
			
			window.document.getElementById(tipo + '-' + orden + '-' + j + '-2').innerHTML = valores[i].precio;
			if(tipo.indexOf('variacion') == 0) {
				var_class = valores[i].variacion_por.indexOf('-') == 0 ? 'variacion baja' : 'variacion sube';
				window.document.getElementById(tipo + '-' + orden + '-' + j + '-3').className = var_class;
				window.document.getElementById(tipo + '-' + orden + '-' + j + '-3').innerHTML = '<strong>' + valores[i].variacion + '</strong> ' + valores[i].variacion_por + '%';
			}
			else if((tipo.indexOf('soporte') == 0) || (tipo.indexOf('resistencia') == 0)) {
				eval("var_class = valores[i]." + tipo + ".indexOf('-') == 0 ? 'variacion baja' : 'variacion sube';");
				if(tipo.indexOf('soporte') == 0)
					dato3 = valores[i].soporte_porcentaje;
					//dato3 = '<strong>' + valores[i].soporte_por + '</strong> ' + valores[i].soporte_porcentaje + '%';
				else if(tipo.indexOf('resistencia') == 0)
					dato3 = valores[i].resistencia_porcentaje;
					//dato3 = '<strong>' + valores[i].resistencia_por + '</strong> ' + valores[i].resistencia_porcentaje + '%';
				window.document.getElementById(tipo + '-' + orden + '-' + j + '-3').className = var_class;
				window.document.getElementById(tipo + '-' + orden + '-' + j + '-3').innerHTML = dato3;
			}
			else {
				eval('dato3 = valores[i].' + tipo);
				var_class = valores[i].variacion_por.indexOf('-') == 0 ? 'variacion baja' : 'variacion sube';
				window.document.getElementById(tipo + '-' + orden + '-' + j + '-3').className = var_class;
				window.document.getElementById(tipo + '-' + orden + '-' + j + '-3').innerHTML = valores[i].variacion_por;
				window.document.getElementById(tipo + '-' + orden + '-' + j + '-4').innerHTML = dato3;
			}
			i++;
			j++;
		}
		if(tipo == 'variacion_por') {
			codigo_valormercado = typeof(valores[0].codigo_mercado) != 'undefined' ? valores[0].codigo_mercado + '_' + valores[0].codigo_valor : valores[0].codigo_valor;
			codigos = codigo_valormercado.split('_');
			codigo_mercado = codigos[0];
			codigo_valor = codigos[1];
			window.document.getElementById('titulo-' + orden).innerHTML = valores[0].indice;
			//if(codigo_mercado == "M")
			//	window.document.getElementById('grafico-' + orden).src = '/graficos/cotizaciones/grafico_' + valores[0].codigo_valor + '.gif';
			//else
				window.document.getElementById('grafico-' + orden).src = '/graficos/historico_ranking.php?mercado=' + codigo_mercado + '&valor=' + codigo_valor;
			seleccionable = window.document.frmGraf.elements['select-' + orden];
			for(i=0; i<5; i++) {
				opcion = new Option(valores[i].indice,valores[i].codigo_valor + '###' + valores[i].indice);
				seleccionable[i+1] = opcion;
			}
		}
	}


	function mostrar_tabla_ar_recomendaciones(tipo,orden,valoresArray) {
		var valores = valoresArray;
		elemento = tipo;
		sufijo_orden = orden == 'min' ? '' : '_r';
		eval('valores.sort(ordenar_numero' + sufijo_orden + ')');
		j = 1;
		i = 0;
		
		if(tipo == 'variacion_por') {
			codigo_valormercado = typeof(valores[0].codigo_mercado) != 'undefined' ? valores[0].codigo_mercado + '_' + valores[0].codigo_valor : valores[0].codigo_valor;
			codigos = codigo_valormercado.split('_');
			codigo_mercado = codigos[0];
			codigo_valor = codigos[1];
			window.document.getElementById('titulo-' + orden).innerHTML = valores[0].indice;
			window.document.getElementById('titulo2-' + orden).innerHTML = valores[0].indice;
			window.document.getElementById('hora-' + orden).innerHTML = valores[0].hora_ver;
			window.document.getElementById('precio-' + orden).innerHTML = valores[0].precio;
			window.document.getElementById('variacion-' + orden).innerHTML = valores[0].variacion;
			window.document.getElementById('variacion_por-' + orden).innerHTML = valores[0].variacion_por;
			//if(codigo_mercado == "M")
			//	window.document.getElementById('grafico-' + orden).src = '/graficos/cotizaciones/grafico_' + valores[0].codigo_valor + '.gif';
			//else
				window.document.getElementById('grafico-' + orden).src = '/graficos/historico_ranking.php?mercado=' + codigo_mercado + '&valor=' + codigo_valor;
			seleccionable = window.document.frmGraf.elements['select-' + orden];
			for(i=0; i<5; i++) {
				opcion = new Option(valores[i].indice,valores[i].codigo_valor + '###' + valores[i].indice + '###' + valores[i].hora_ver + '###' + valores[i].precio + '###' + valores[i].variacion + '###' + valores[i].variacion_por);
				seleccionable[i+1] = opcion;
			}
		}

		//new valInd(valor[i], precios[i], aperturas[i], maximos[i], minimos[i], anteriores[i], variaciones[i], variaciones_por[i], volumenes[i], volumenes_ver[i], horas[i], horas_ver[i], codigos_valor[i]);
	}
	
	function selGrafico(orden) {
		seleccionable = window.document.frmGraf.elements['select-' + orden];
		if(seleccionable.selectedIndex > 0) {
			datosValor = seleccionable.options[seleccionable.selectedIndex].value.split('###');
			codigos = datosValor[0].split('_');
			codigo_mercado = codigos[0];
			codigo_valor = codigos[1];
			window.document.getElementById('titulo-' + orden).innerHTML = datosValor[1];
			//if(codigo_mercado == "M")
			//	window.document.getElementById('grafico-' + orden).src = '/graficos/cotizaciones/grafico_' + datosValor[0] + '.gif';
			//else
				window.document.getElementById('grafico-' + orden).src = '/graficos/historico_ranking.php?mercado=' + codigo_mercado + '&valor=' + codigo_valor;
		}
	}

	function selGraficoRecomendaciones(orden) {
		seleccionable = window.document.frmGraf.elements['select-' + orden];
		if(seleccionable.selectedIndex > 0) {
			datosValor = seleccionable.options[seleccionable.selectedIndex].value.split('###');
			codigos = datosValor[0].split('_');
			codigo_mercado = codigos[0];
			codigo_valor = codigos[1];
			window.document.getElementById('titulo-' + orden).innerHTML = datosValor[1];
			window.document.getElementById('titulo2-' + orden).innerHTML = datosValor[1];
			window.document.getElementById('hora-' + orden).innerHTML = datosValor[2];
			window.document.getElementById('precio-' + orden).innerHTML = datosValor[3];
			window.document.getElementById('variacion-' + orden).innerHTML = datosValor[4];
			window.document.getElementById('variacion_por-' + orden).innerHTML = datosValor[5];
			//if(codigo_mercado == "M")
			//	window.document.getElementById('grafico-' + orden).src = '/graficos/cotizaciones/grafico_' + datosValor[0] + '.gif';
			//else
				window.document.getElementById('grafico-' + orden).src = '/graficos/historico_ranking.php?mercado=' + codigo_mercado + '&valor=' + codigo_valor;
		}
	}

	function valInd(indice, precio, apertura, maximo, minimo, anterior, variacion, variacion_por, volumen, volumen_ver, hora, hora_ver, codigo_valor) {
		this.indice = indice;
		this.precio = precio;
		this.apertura = apertura;
		this.maximo = maximo;
		this.minimo = minimo;
		this.anterior = anterior;
		this.variacion = variacion;
		this.variacion_por = variacion_por;
		this.volumen = volumen;
		this.volumen_ver = volumen_ver;
		this.hora = hora;
		this.hora_ver = hora_ver;
		this.codigo_valor = codigo_valor;
	}

	function valRat(indice, precio, per, bpa, rentxdiv, prvalor, payout, beta, alfa, corranual, volatanual, codigo_valor, codigo_mercado, variacion_por) {
		this.indice = indice;
		this.precio = precio;
		this.per = per;
		this.bpa = bpa;
		this.rentxdiv = rentxdiv;
		this.prvalor = prvalor;
		this.payout = payout;
		this.beta = beta;
		this.alfa = alfa;
		this.corranual = corranual;
		this.volatanual = volatanual;
		this.codigo_valor = codigo_valor;
		this.codigo_mercado = codigo_mercado;
		this.variacion_por = variacion_por;
	}

	function valTec(indice, precio, soporte, resistencia, variacion_por, codigo_mercado) {
		this.indice = indice;
		this.precio = precio;
		this.soporte_por=String((Math.floor((soporte - precio)*100))/100);
		this.resistencia_por=String((Math.floor((resistencia - precio)*100))/100);
		this.soporte_porcentaje = soporte;
		this.resistencia_porcentaje = resistencia;
		this.variacion_por = variacion_por;
		this.codigo_mercado = codigo_mercado;
		
	}

	function ordenar_texto(a, b) {
		an = eval("a." + elemento);
		bn = eval("b." + elemento);
		if (an < bn) {
			return -1;	
		}	
		else if (an > bn) {
			return 1;	
		}
		else {
			return 0;	
		}
	}
	
	function ordenar_numero(a, b) {
		an = Number(eval("a." + elemento));
		bn = Number(eval("b." + elemento));
		if (an < bn) {
			return -1;	
		}	
		else if (an > bn) {
			return 1;	
		}
		else {
			return 0;	
		}
	}
		
	function ordenar_texto_r(a, b) {
		an = eval("a." + elemento);
		bn = eval("b." + elemento);
		if (an < bn) {
			return 1;	
		}	
		else if (an > bn) {
			return -1;	
		}
		else {
			return 0;	
		}	
	}
	
	function ordenar_numero_r(a, b) {
		an = Number(eval("a." + elemento));
		bn = Number(eval("b." + elemento));
		if (an < bn) {
			return 1;	
		}	
		else if (an > bn) {
			return -1;	
		}
		else {
			return 0;	
		}
	}
		
	function annadirFav(indice) {
		var http = createRequestObject();
		http.open('get', '/backend/anadir_favorito.php?valor=' + indice + '&r=' + Math.random());
		http.onreadystatechange = function () {
			if(http.readyState == 4){
				if (http.responseText) {
					if (http.responseText.indexOf('REGISTRO') != -1) {
						window.location.href='/registro/';	
					}	
					else if (http.responseText.indexOf('ERROR') != -1) {
						alert('Ha ocurrido un error al añadir el valor, por favor, intentelo más tarde.');	
					}	
					else {
						alert('Valor añadido, gracias.');
					}
					
				}
			}
		};
		http.send(null);
	}

