﻿pos_filename = 0;
pos_titulo = 1;
pos_tipo = 2;
pos_regiones = 3;
pos_temas = 4;
pos_autores = 5;
pos_copy = 6;
/*
 |	Busqueda de string (word) en primera posicion
 |	de un array bidimensional (arr)
*/
function arrSearch(word,arr) 
	{

	if (arr.length==0)
		{
		return -1;
		}
	var arr_pos=0;
	while (arr_pos<arr.length) 
		{
		if (word!=arr[arr_pos][0])
			{
			arr_pos++;
			}
		else
			{
			return arr_pos;
			}
		}
	return -1;
	}


function partialMatch(limit,exced)
	{
	limit_Reg = new RegExp("^"+limit);
	if (limit_Reg.test(exced))
		{
		return true;
		}
	return false;
	}



/*
 | Devuelve posicion si halla item en arr, sino -1
*/
function arrayHasItem(item,arr) 
	{
	//alert("hola");
	if (arr.length==0)
		{
		//alert("arrayHasItem length es 0");
		return -1;
		}
	var has_pos=0;
	while (has_pos<=arr.length) 
		{
		if (item!=arr[has_pos])
			{
			has_pos++;
			}
		else
			{
			//alert("arrayHasItem at pos "+has_pos);
			return has_pos;
			}
		}
	//alert("arrayHasItem at pos -1");
	return -1;
	}
/*
 | Busqueda binaria
*/
function bsearch(word,arr) 
	{
	var izq=0;
	var der=arr.length;
	var m;
	m = Math.floor((izq+der)/2);
	while ((izq<=der)&&(m<arr.length))
		{
		if (word < arr[m]) 
			der=m-1;
		else if (word >arr[m])
			izq=m+1;
		else return m;
		m = Math.floor((izq+der)/2);
		}
	nearest.pos = m;
	return null;
	}

function myComp(a,b)
	{
	if (a[1]<b[1]) return -1;
	else if (a[1]>b[1]) return 1;
	else if (a[2]<b[2]) return -1;
	else if (a[2]>b[2]) return 1;
	else return 0;
	}
												

function validation()
	{
	form = document.form_busq
	/// Valida el input
	if (form.word.value == '')
		{
		alert('Debe ingresar algun termino a buscar');
		form.word.focus()
		return false;
		}
	
	if (form.tipo_fijo == "")
		{
		if ((!form.tipo[0].checked) && (!form.tipo[1].checked))
			{
			alert('Debe elegir algun tipo');
			form.tipo[0].focus();
			return false;
			}
		}
	if (choices.desde > choices.hasta)
		{
		alert('Debe elegir un rango valido de fechas.');
		form.hasta.focus();
		return false;
		}


	az_Reg = new RegExp("[^A-Za-z0-9_]","g");
	for(v in choices.word_list) 
		{
		if (az_Reg.test(choices.word_list[v]))
			{
			alert('Caracteres no validos en el texto de busqueda.');
			return false;
			}
		}


	return true;
	}


/*
 | Encapsula opciones del form
*/
function Choices(form){
	// Filtro articulos-resenias

	this.articulos = 2;
	this.resenias = 3;

	/*if (form.tipo_fijo.value == 2)
		{
		this.articulos = form.tipo_fijo.value;
		this.resenias = false;
		}
	else
		{
		if (form.tipo[0].checked)
			{
			this.articulos = form.tipo[0].value;
			}
		if (form.tipo[1].checked)
			{
			this.resenias = form.tipo[1].value;
			}
		}	
	*/
	// Filtro opciones palabras (radio)
	if (form.opcionesWord[0].checked)
		{
		this.everyWord = true;
		}
	else 
		{
		this.anyWord = true;
		}
		
	// Filtro por numero de edicion
	this.desde = new Number(form.desde[form.desde.selectedIndex].value)
	this.hasta = new Number(form.hasta[form.hasta.selectedIndex].value)


	// Filtro temas
	this.temas_todos = form.temas_todos.checked;
	this.temas = new Array();
	for (num_tema=0;num_tema<form.temas.length;num_tema++)
		{
		if (form.temas[num_tema].checked)
			{
			this.temas[this.temas.length] = form.temas[num_tema].value
			}
	
		}
		
	// Filtro regiones
	this.region_todos = form.region_todos.checked;
	this.region = new Array();
	count_regiones = 0
	for (num_region=0;num_region<form.region.length;num_region++)
		{
		if (form.region[num_region].checked)
			{
			this.region[this.region.length] = form.region[num_region].value
			count_regiones ++
			}
		
		}
	if (count_regiones == form.region.length)
		{
		this.region_todos = true;
		}

	// Filtro Autores
	if (form.autor[form.autor.selectedIndex].value=="autores_todos")
		{
		this.autor_todos = true;
		}
	else
		{
		this.autor = new Array(form.autor[form.autor.selectedIndex].value);
		}


	// Descomposicion el input en palabras
	separator = /,|\s/g;
	this.word_list = form.word.value.split(separator);
	
	if (this.word_list.length==1)
		{
		this.everyWord=false;
		this.anyWord=true;
		}
		


	// Filtro copyright
	this.copy_todos = form.copy_todos.checked;
	this.copy = new Array();
	for (num_copy=0;num_copy<form.copy.length;num_copy++)
		{
		if (form.copy[num_copy].checked)
			{
			this.copy[this.copy.length] = form.copy[num_copy].value
			}
	
		}

	}


function typeMatch(ref_Int)	{
	if (typeof ref_Int == 'undefined' || typeof file_Lst[ref_Int] == 'undefined'){
		return false;
	}
	if (file_Lst[ref_Int][pos_tipo]==1)	{
		// es resenia
		if (choices.resenias)
			{
			//alert("typeMatch es reseña")
			return true;
		}
	}
	if (file_Lst[ref_Int][pos_tipo]==0)	{
		// es nota
		if (choices.articulos)
			{
			//alert("typeMatch articulo")
			return true;
		}
	}
	return false;
}


function arrayIntersection(array1, array2)
	{
	for (k in array1)
		{
		for (j in array2)
			{
			if (array1[k] == array2[j])
				{
				return true;
				}
			}
		}
	return false;
	}

/*
 |	Devuelve verdadero si las opciones del usuario
 |	coinciden con las de la referencia recibida
 |	como parametro.
*/
function incluirEstaReferencia(ref_Int)
	{
	//alert("entrando a incluirEstaReferencia("+ref_Int+")")
	// TIPO
	if (((choices.articulos) && (choices.resenias)) || (typeMatch(ref_Int)))
		{
			//alert("pase incluirEstaReferencia tipo")
		// FECHA
		if (typeof file_Lst[ref_Int] == 'undefined'){return false;}
		var inc_numero = file_Lst[ref_Int][0].split('-')[0];
		inc_numero_Int = new Number(inc_numero);
		//alert("incluirEstaReferencia Fecha "+inc_numero_Int)
		//alert("inc_numero_Int["+inc_numero_Int+"] >= choices.desde["+choices.desde+"] AND inc_numero_Int["+inc_numero_Int+"] <= choices.hasta["+choices.hasta+"]")
		if ((inc_numero_Int >= choices.desde) && (inc_numero_Int <= choices.hasta))
			{
			//alert("pase las fechas")
			// TEMAS
			if ((choices.temas_todos) || (file_Lst[ref_Int][pos_temas]=="") || (arrayIntersection(choices.temas,file_Lst[ref_Int][pos_temas].split(','))))
				{
				// REGIONES
				if ((choices.region_todos) || (file_Lst[ref_Int][pos_regiones]=="") || (arrayIntersection(choices.region, file_Lst[ref_Int][pos_regiones].split(','))))
					{
					// COPY
					if ((choices.copy_todos) || (file_Lst[ref_Int][pos_copy]=="") || (arrayIntersection(choices.copy, file_Lst[ref_Int][pos_copy].split(','))))
						{
						// AUTORES
						if ((choices.autor_todos) || (file_Lst[ref_Int][pos_autores]=="") || (arrayIntersection(choices.autor,file_Lst[ref_Int][pos_autores].split(','))))
							{
							//alert("incluirEstaReferencia(ref_Int) devuelve TRUE")
							return true;
							}
						}
					}
				}
			}
		}
	//alert("incluirEstaReferencia(ref_Int) devuelve FALSO")
	return false;
	}

function replaceEntities(repl_word)
	{
	repl_word_Str = new String(repl_word);
	for (entitie_Int=0; entitie_Int<entities_Lst.length; entitie_Int++)
		{
		repl_word_Str = repl_word_Str.replace(entities_Lst[entitie_Int][0], entities_Lst[entitie_Int][1])
		}
	return repl_word_Str.toLowerCase()
	}

function Nearest()
	{
	this.pos = 0;
	}

function search() 
	{
	out = '';
	result_header = '';
	result_links = '';
	total_results = 0;
	choices = new Choices(document.form_busq);
	if (!validation())
		{
		return false;
		}
	nearest = new Nearest();
	var result_list = new Array();

	j = 0;
	for(i in choices.word_list) 
		{
		word = replaceEntities(choices.word_list[i]);
		var x = bsearch(word,term_Lst);
		if (x!=null) 
			{
			// indices obtenidos por macheo exacto
			result_list[j] = String(x);
			j++;
			}

		else
			{
			wordLen_Int = word.length;
			for (possible_Int=nearest.pos -2;possible_Int<=nearest.pos+2;possible_Int++)
				{
				if ((possible_Int<term_Lst.length) && (wordLen_Int < term_Lst[possible_Int].length) && (wordLen_Int>term_Lst[possible_Int].length/2))
					{
					if (partialMatch(word, term_Lst[possible_Int]))
						{
						result_list[j] = String(possible_Int);
						j++;
						break;
						}
					}
				else if (term_Lst[possible_Int].length>wordLen_Int/2)
					{
					if (partialMatch(term_Lst[possible_Int], word))
						{
						result_list[j] = String(possible_Int);
						j++;
						break;
						}
					}
				}
		}
	}


		
	// mostramos los resultados
	if ((result_list.length==0) || ((choices.everyWord) && (result_list.length!=choices.word_list.length)))
		{
		//result_header += '<p><strong>No se encontraron documentos con los criterios seleccionados</strong></p>';
		}
	else
		{
		if (choices.everyWord)
			{
			candidates_Lst = new Array(0);
			succesfullCandidates_Lst = new Array(0);
			}
		else
			{
			ref_list = new Array(0);
			}
		
		for(r in result_list) 
			{
			if ((result_list[r]!='') && (result_list[r]!=null)) 
				{
				thisRel_Lst = rel_Lst[result_list[r]].split(',');
				resChecked = false;
				for (i=0;i<thisRel_Lst.length; i++) 
					{
					ref_Int = thisRel_Lst[i];
					if (incluirEstaReferencia(ref_Int))
						{
						if (choices.anyWord)
							{
							if (ref_list.length!=0)
								{
								i_ref = arrSearch(ref_Int,ref_list);
								}
							else
								i_ref = -1;
							if (i_ref== -1)
								{
								// Todavia no aparecio esta referencia
								ref_list[ref_list.length] = new Array(ref_Int,result_list.length,i);
								}
							else 
								{
								// Decrementamos cant de apariciones en esta referencia
								ref_list[i_ref][1] = ref_list[i_ref][1] - 1;
								// Sumamos posicion relativa de las apariciones en esta ref
								ref_list[i_ref][2] = ref_list[i_ref][2] + i;
								}
							} 
						else
							{
							if (arrayHasItem(r,succesfullCandidates_Lst)<0)
								{
								succesfullCandidates_Lst[succesfullCandidates_Lst.length] = r
								}
							// Todas las palabras
							if (r==0)
								{
								pos_new = candidates_Lst.length;
								candidates_Lst[pos_new] = new Array(ref_Int, true);
								}
							else if (!resChecked)
								{
								resChecked = true;
								for (k=0; (k<candidates_Lst.length) ; k++)
									{
									if(arrayHasItem(candidates_Lst[k][0], rel_Lst[result_list[r]].split(',')) < 0)
										{
										candidates_Lst[k][1] = false;
										}
									}
								}
							}
						}
					}
				}
			}

		/*
		Mostramos los resultados
		*/

		if ((choices.anyWord) || (choices.everyWord) && (succesfullCandidates_Lst.length==result_list.length))
			{
			if (choices.anyWord)
				{
				ref_list.sort(myComp);
				var numberOfResults = ref_list.length;
				}
			else
				{
				var numberOfResults = candidates_Lst.length;
				}
			//alert("numberOfResults "+numberOfResults);
			result_links += '<OL>';
			for (r=0;r<numberOfResults;r++) 
				{
				if (choices.anyWord)
					{
					ref = ref_list[r][0];
					}
				else
					{
					if (candidates_Lst[r][1])
						{
						ref = candidates_Lst[r][0];
						}
					else
						{
						ref = -1;
						}
					}
				
				if (ref>-1)
					{
					total_results++;
					if (file_Lst[ref][pos_tipo]==1)
						{
						// Resenias
						book_id = file_Lst[ref][0].split('-')[1]
						result_links += '<LI><A HREF="../../../../NODE/'+book_id+'.HTM">'+file_Lst[ref][1]+'</A> <SPAN CLASS="cant">(<I>Rese&ntilde;a de libro</I>)</SPAN></LI>';
						}
					else
						{
						// Notas
						article_id = file_Lst[ref][0].split('-')[1];
						result_links += '<LI><A HREF="../../../../NODE/'+article_id+'.HTM">'+file_Lst[ref][1]+'</A> <SPAN CLASS="cant">(<STRONG>Art&iacute;culo</STRONG>)</SPAN></LI>';
						}
					}
				}
			}
	}

	//alert("total_results "+total_results);
	// header de los resultados
	if (total_results > 0)
		{
		//alert("HAY "+total_results+" RESULTADOS");
		result_header += '<H3>Se encontraron '+ total_results +' resultado/s para su b&uacute;squeda.</H3>' ;
		}
	else
		{
		//alert("NOOOOOOOOO HAY RESULTADOS");
		result_header += '<H3>No hubo resultados que satisfagan las condiciones. <BR> &iquest;Desea volver al <A HREF="javascript:document.form_busq.word.focus();">formulario de b&uacute;squeda?</A></H3>';
		}

	result_links += '</OL>';
	out += result_header;
	out += result_links;
	if (typeof brws != 'undefined' && brws == '_ie'){
		out += '<p style="color:#999999;"><b>Nota:</b> Es posible que su navegador web no permita arrojar todos los resultados de su b&uacute;squeda. <br />Para una mejor navegaci&oacute;n de este CD sugerimos utilizar el navegador web <a href="http://www.mozilla-europe.org/es/firefox/">Firefox</a>. <br />(El navegador que Ud. está usando ahora tiene un l&iacute;mite de memoria que no le permite cargar el &iacute;ndice completo.)</p>';
	}
	out += '<P>Volver al <A HREF="javascript:document.form_busq.word.focus();">formulario de b&uacute;squeda.</A></P>'	
	showResults(out);
	return false;
} // fin funcion




function showResults(Results_Str){
	document.getElementById("divResultados").innerHTML = Results_Str;
	if (window.top.location.href.toLowerCase().indexOf('avanzada') != -1){
		window.scrollTo(0,850);
	} else {
		window.scrollTo(0,300);		
	}
}


function actualizacion(field)
	{
	form = document.form_busq;
	var target = field.name;
	var radioTodos = eval('form.' + target + '_todos');
	var group = eval('form.' + target);
	
	if (field.checked)
		{
		// Hay un check selecionado, des-seleciono el radio
		if (radioTodos.checked)
			{
			radioTodos.checked = false;
			}
		}
	else
		{
		// Hay un check des-seleccionado, revisamos que quede alguno seleccionado
		for (i=0;i<group.length;i++)
			{
			if (group[i].checked)
				{
				return true;
				radioTodos.checked = false;
				}
			}
		// Ninguno de los temas esta seleccionado, selecciono el radio
		radioTodos.checked = true;
		}
	return true;
	}


var entities_Lst = new Array(
new Array(new RegExp("ç","gi"),"c"),
new Array(new RegExp("õ","gi"),"o"),
new Array(new RegExp("ù","gi"),"u"),
new Array(new RegExp("ï","gi"),"i"),
new Array(new RegExp("í","gi"),"i"),
new Array(new RegExp("oe","gi"),"oe"),
new Array(new RegExp("ú","gi"),"u"),
new Array(new RegExp("á","gi"),"a"),
new Array(new RegExp("ë","gi"),"e"),
new Array(new RegExp("ê","gi"),"e"),
new Array(new RegExp("è","gi"),"e"),
new Array(new RegExp("â","gi"),"a"),
new Array(new RegExp("ü","gi"),"u"),
new Array(new RegExp("ö","gi"),"o"),
new Array(new RegExp("ä","gi"),"a"),
new Array(new RegExp("ò","gi"),"o"),
new Array(new RegExp("î","gi"),"i"),
new Array(new RegExp("ô","gi"),"o"),
new Array(new RegExp("ae","gi"),"ae"),
new Array(new RegExp("ó","gi"),"o"),
new Array(new RegExp("à","gi"),"a"),
new Array(new RegExp("ã","gi"),"a"),
new Array(new RegExp("ñ","gi"),"n"),
new Array(new RegExp("é","gi"),"e"));
