// JavaScript Document
	
	/*Si se reubica o se cambia el nombre de la URL de base, sólo es necesario modificar aquí*/
	/* prefijo = "http://buscador.chileclic.cl/"; */
	var prefijo = "http://buscador.chileclic.cl/";

	/* Se maneja variable global para posicionar la fila de sugerencia */
	var pos_suger = -1;
	
	/* Funciones para codificar y decodificar UTF-8 */
	/* UTF8 encoding/decoding functions
	 * Copyright (c) 2006 by Ali Farhadi.
	 * released under the terms of the Gnu Public License.
	 * see the GPL for details.
	 *
	 * Email: ali[at]farhadi[dot]ir
	 * Website: http://farhadi.ir/
	 */

	//an alias of String.fromCharCode
	function chr(code)
	{
		return String.fromCharCode(code);
	}

	//returns utf8 encoded charachter of a unicode value.
	//code must be a number indicating the Unicode value.
	//returned value is a string between 1 and 4 charachters.
	function code2utf(code)
	{
		if (code < 128) return chr(code);
		if (code < 2048) return chr(192+(code>>6)) + chr(128+(code&63));
		if (code < 65536) return chr(224+(code>>12)) + chr(128+((code>>6)&63)) + chr(128+(code&63));
		if (code < 2097152) return chr(240+(code>>18)) + chr(128+((code>>12)&63)) + chr(128+((code>>6)&63)) + chr(128+(code&63));
	}

	//it is a private function for internal use in utf8Encode function 
	function _utf8Encode(str)
	{	
		var utf8str = new Array();
		for (var i=0; i<str.length; i++) {
			utf8str[i] = code2utf(str.charCodeAt(i));
		}
		return utf8str.join('');
	}

	//Encodes a unicode string to UTF8 format.
	function utf8Encode(str)
	{	
		var utf8str = new Array();
		var pos,j = 0;
		var tmpStr = '';
		
		while ((pos = str.search(/[^\x00-\x7F]/)) != -1) {
			tmpStr = str.match(/([^\x00-\x7F]+[\x00-\x7F]{0,10})+/)[0];
			utf8str[j++] = str.substr(0, pos);
			utf8str[j++] = _utf8Encode(tmpStr);
			str = str.substr(pos + tmpStr.length);
		}
		
		utf8str[j++] = str;
		return utf8str.join('');
	}

	//it is a private function for internal use in utf8Decode function 
	function _utf8Decode(utf8str)
	{	
		var str = new Array();
		var code,code2,code3,code4,j = 0;
		for (var i=0; i<utf8str.length; ) {
			code = utf8str.charCodeAt(i++);
			if (code > 127) code2 = utf8str.charCodeAt(i++);
			if (code > 223) code3 = utf8str.charCodeAt(i++);
			if (code > 239) code4 = utf8str.charCodeAt(i++);
			
			if (code < 128) str[j++]= chr(code);
			else if (code < 224) str[j++] = chr(((code-192)<<6) + (code2-128));
			else if (code < 240) str[j++] = chr(((code-224)<<12) + ((code2-128)<<6) + (code3-128));
			else str[j++] = chr(((code-240)<<18) + ((code2-128)<<12) + ((code3-128)<<6) + (code4-128));
		}
		return str.join('');
	}

	//Decodes a UTF8 formated string
	function utf8Decode(utf8str)
	{
		var str = new Array();
		var pos = 0;
		var tmpStr = '';
		var j=0;
		while ((pos = utf8str.search(/[^\x00-\x7F]/)) != -1) {
			tmpStr = utf8str.match(/([^\x00-\x7F]+[\x00-\x7F]{0,10})+/)[0];
			str[j++]= utf8str.substr(0, pos) + _utf8Decode(tmpStr);
			utf8str = utf8str.substr(pos + tmpStr.length);
		}
		
		str[j++] = utf8str;
		return str.join('');
	}	
	/* Fin Funciones para codifcar y decodificar UTF-8 */



	/* Estas dos funciones permiten la implementación de la sugerencia de resultados mientras escribe */
	function lookup(inputString,e) {

		var keycode;
		if (window.event) 
		{
			keycode = window.event.keyCode;
		}
		else if (e) 
		{
			keycode = e.which;	
		}
		else
		{
		}


		if (keycode!=13 && keycode!=27 && keycode!=38 && keycode!=40) {
			if(inputString.length == 0) {
				// Hide the suggestion box.
				$('#suggestions').hide();
			} else {
				$.post(__proxy+"rpc.php", {queryString: ""+inputString+""}, function(data){
					pos_suger = -1;
					if(data.length >1) {
						$('#suggestions').show();
						$('#autoSuggestionsList').html("<table id='sugerTabla'><tbody>"+data+"</tbody></table>");
					}else{
					   $('#suggestions').hide();
					}
				});
			}
		}
	} // lookup
	
	function limpia_sugerencias(thisValue) {
		setTimeout("$('#suggestions').hide();", 200);
	}

	function fill(thisValue) {
		$('#id_consulta').val(thisValue);
		setTimeout("$('#suggestions').hide();", 200);
		Submite(0);
	}
	
	function oscurece(pos) {
		var sugerTabla = document.getElementById("sugerTabla");
		
		if (pos_suger > -1) {
			sugerTabla.rows[pos_suger].className="normal";
		}
		sugerTabla.rows[pos].className="sobre";
		pos_suger = pos;
		
		var caja = document.getElementById("caja_busqueda");
			caja[0].value = sugerTabla.rows[pos_suger].cells[0].innerHTML;
		return false;
	}
	/* FIN estas funciones permiten la implementación de la sugerencia de resultados mientras escribe */

	/* Esta función captura el evento "click" y así se guarda un log de los click hechos en el buscador */
	function catchevent(event) {

		if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null))
		{
			es_fire_fox = false;
			targetedControl = event.srcElement;
		}
		else
		{
			es_fire_fox = true;
			targetedControl = event.target;
		}

		if (targetedControl.href == undefined) {}
		else
		{
			var radio1 = document.getElementsByName("RadioGroup1");
			var caja = document.getElementById("caja_busqueda");

			/* Ciudades Digitales: Si se agrega o elimina un botón de refinamiento se debe modificar aquí */
			if (radio1[1].checked)
				{boton=1;}
			else if (radio1[2].checked)
				{boton=2;}
			else if (radio1[3].checked)
				{boton=3;}
			else if (radio1[4].checked)
				{boton=4;}
			else	
				{boton=0;}

			if (es_fire_fox)
			{
				/* Reemplazar "&" por %26 en la que query*/
				caja[0].value = caja[0].value.replace(/&/g, '%26');
				url_ref = targetedControl.href.replace(/&/g, '%26');
				window.location.href = prefijo+'write_log.php?href='+url_ref+'&query='+caja[0].value+'&refina='+boton+'&fire=1';
				return false;
			}
			else
			{
				/* Reemplazar "&" por %26 en la que query*/
				caja[0].value = caja[0].value.replace(/&/g, '%26');
				url_ref = targetedControl.href.replace(/&/g, '%26');
				event.srcElement.href = prefijo+'write_log.php?href='+url_ref+'&query='+caja[0].value+'&refina='+boton+'&fire=0';
			}
			/*sleep(1000);*/
		}	
	}

	function sleep(milliseconds) {
		var start = new Date().getTime();
		
		for (var i = 0; i < 1e7; i++) {
			if ((new Date().getTime() - start) > milliseconds){
				break;
			}

		}

	}
	
	/* Esta función captura el valor del parámetro de la URL correspondiente a la variable indicada en "varname" */
	function getValue(varname)
	{
		var url = window.location.href;	/* First, we load the URL into a variable */
  		var qparts = url.split("?");	/*  Next, split the url by the ? */

  		/*  Check that there is a querystring, return "" if not */
  		if (qparts.length < 2)
  		{
    		return "";
  		}

  		var query = qparts[1];			/*  Then find the querystring, everything after the ? */
  		var vars = query.split("&");	/*  Split the query string into variables (separates by &s) */
  		var value = "";					/*  Initialize the value with "" as default */

  		/*  Iterate through vars, checking each one for varname */
  		for (i=0;i<vars.length;i++)
  		{
    		/*  Split the variable by =, which splits name and value */
    		var parts = vars[i].split("=");
    
    		/*  Check if the correct variable */
    		if (parts[0] == varname)
    		{
      			/*  Load value into variable */
      			value = parts[1];
      			/*  End the loop */
      			break;
    		}
		}
  
  		/*  Convert escape code */
  		value = unescape(value);

		/*  Convert "+"s to " "s */
		value.replace(/\+/g," ");
		value.replace(/\134/g,"");

  		/*  Return the value */
  		return value;
      }

	  /* Ciudades Digitales: en esta función se construye el buscador y las condiciones bajo las cuales se ejecutará */
      function cse() {

        var sFormDiv = document.getElementById("id_searchForm");
        var leftScDiv = document.getElementById("leftSearchControl");
 
		/*      create a left search control, create a custom search form */
        leftControl = new google.search.SearchControl();
		leftControl.setNoResultsString("No hay resultados para su consulta");
        buscaForm = new google.search.SearchForm(true, sFormDiv);
 
		/*      set up for large result sets */
        leftControl.setResultSetSize(GSearch.LARGE_RESULTSET);
        leftControl.setLinkTarget(GSearch.LINK_TARGET_SELF);

		/*      configure left control Site Restrict to CSE ID for Search */
		var cseId_Transparencia ="009673987297622511854:dcpcxycquak";	/* Buscador Transparencia */
        var cseId_Emprendimiento = "009673987297622511854:qyjetrksv4i";	/* Buscador Emprendimiento */
		var cseId = "";

		boton_refinamiento = getValue("refina");

		//Si se encuentra un texto de sugerencia lo muestra junto con el resultado de la búsqueda
		quiso_decir = getValue("qd");
		if (quiso_decir != "") {
			var sugiere = document.getElementById("sugerencias");
			var s1 = document.createElement("s1");
			s1.innerHTML = "<br>Quiz&aacute;s quiso decir: <a class='referencia' href='"+prefijo+"buscar.php?consulta="+quiso_decir+"&refina="+boton_refinamiento+"'>"+quiso_decir+"</a><br><br>";
			sugiere.appendChild(s1);
		}
		
		/* Ciudades Digitales: Si se agrega o elimina un botón de refinamiento se debe modificar aquí */
		/* dado que puede haber cambiado el número del botón de Emprendimiento*/
		if (boton_refinamiento=="1")
			{cseId = cseId_Emprendimiento;}
		else
			{cseId = cseId_Transparencia;}

		searcher = new google.search.WebSearch();
        options = new google.search.SearcherOptions();
        searcher.setSiteRestriction(cseId);
		
		/* Si se ha indicado el parámetro SafeSearch se coloca la restricción */
		sf = getValue("sf");
		if (sf=="" | sf=="f") {
			searcher.setRestriction(google.search.Search.RESTRICT_SAFESEARCH,
                        			google.search.Search.SAFESEARCH_OFF);
		}
		else {
			searcher.setRestriction(google.search.Search.RESTRICT_SAFESEARCH,
									google.search.Search.SAFESEARCH_STRICT);
		}
		
		var titulo = "Resultados Busqueda";
		searcher.setUserDefinedLabel(titulo);
		options.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
        leftControl.addSearcher(searcher,options); 
 
 /*		draw the left control */
        var drawOptions = new google.search.DrawOptions();
        drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_LINEAR);
        leftControl.draw(leftScDiv); 

	  	consulta_externa = getValue("consulta");
/*		Esta consulta sólo se ejecutará cuando venga desde el portal o cuando se llame con parámetros*/
	  	if (consulta_externa != "")
		{
			/* Se habilita la nube lateral y se deshabilita la inferior */
			var lateral = document.getElementById("tag_lateral");
			var inferior = document.getElementById("tag_inferior");
			lateral.className="ocupado";
			inferior.className="ocupado";

			/* Captura el parámetro que indica la etiqueta de refinamiento seleccionada */
			boton_refinamiento = getValue("refina");
			var caja = document.getElementById("caja_busqueda");
			consulta_externa = utf8Decode(consulta_externa);

			caja[0].value = consulta_externa.replace(/\134/g,"");
			caja[0].className="ocupado";

			leftControl.setNoResultsString("No hay resultados para su consulta");
			/* Siempre limpia las opciones adicionales de la búsqueda */
			searcher.setQueryAddition("");
			var radio1 = document.getElementsByName("RadioGroup1");

			/* Ciudades Digitales: Si se agrega o elimina un botón de refinamiento se debe modificar aquí */
			if (boton_refinamiento=="4") {
				radio1[4].checked = true;
				searcher.setQueryAddition("more:ChileClic");			
			}
			else if (boton_refinamiento=="2") {
       			radio1[2].checked = true;
				searcher.setQueryAddition("more:Transparencia");
			}
			else if (boton_refinamiento=="3") {
				radio1[3].checked = true;
				searcher.setQueryAddition("more:Municipios");
			}
			/* Ciudades Digitales: esto gatilla llamar al buscador de Emprendimiento */
			else if (boton_refinamiento=="1") {
				radio1[1].checked = true;
				searcher.setQueryAddition(""); /* para que funcione esto DEBE haber sido configurado el motor de Emprendimiento */
			}
			else {
				radio1[0].checked = true;
				searcher.setQueryAddition("");
			}
			/* Reemplazar "&" por %26 en la que query*/
			consulta_externa = consulta_externa.replace(/&/g, '%26');
			leftControl.execute(consulta_externa);	
		}
		else {
			/* Se habilita la nube inferior y se deshabilita la Lateral */
			var lateral = document.getElementById("tag_lateral");
			var inferior = document.getElementById("tag_inferior");
			lateral.className="vacio";
			inferior.className="vacio";
		}

	  }

      function Submite(externo){
		var caja = document.getElementById("caja_busqueda");
		var radio1 = document.getElementsByName("RadioGroup1");
		
		/* Ciudades Digitales: Si se agrega o elimina un botón de refinamiento se debe modificar aquí */
		if (radio1.length != 0) {
			if (radio1[1].checked)
				{boton=1;}
			else if (radio1[2].checked)
				{boton=2;}
			else if (radio1[3].checked)
				{boton=3;}
			else if (radio1[4].checked)
				{boton=4;}
			else
				{boton=0;}
		}
		else
				{boton=0;}		
			
		/* Reemplazar "&" por %26 en la que query*/
		caja[0].value = caja[0].value.replace(/&/g, '%26');
		if (externo=="1") {
			var opciones = "width=1000,height=600,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes";
			mi_ventana = window.open("","",opciones);
			mi_ventana.document.write(" ");
			mi_ventana.location.href=prefijo+"write_log.php?query="+caja[0].value+"&refina="+boton+"&ext="+externo+"&origen="+document.referrer;
		}
		else
			window.location.href=prefijo+"write_log.php?query="+caja[0].value+"&refina="+boton;

        return false;
	  }

	  function OnLoad() {
        new cse();
      }
	  
	  function limpiarBusqueda(origen){
		if(origen.value=="")
		{
			origen.className="ocupado";
		}
	  }

	  function restaurarBusqueda(origen){
		var radio1 = document.getElementsByName("RadioGroup1");
	  	if(origen.value=="") {
			if (radio1.length != 0)		
				radio1[0].checked = true;
			origen.className="vacio";
		}
		else
			origen.className="ocupado";
	  }

	  /* Esta función reconoce el <enter> como un Submit */
	  function Simula_Submit(origen,e,externo){
	  	var keycode;
		if (window.event) 
		{
			keycode = window.event.keyCode;
		}
		else if (e) 
		{
			keycode = e.which;	
		}
		else
		{
			if(origen.value=="") {
				if (radio1.length != 0)
					radio1[0].checked = true;
				return true;
			}
		}
		
		if (keycode == 13)
   		{
   			Submite(externo);
   			return false;
   		}
		/* Flecha hacia abajo */
		else if (keycode == 40) {
			var sugerencia = document.getElementById("suggestions");
			if (sugerencia.style.display != 'none') {
				var sugerTabla = document.getElementById("sugerTabla");
				if (pos_suger<sugerTabla.rows.length-1 && pos_suger<9) {
					/*sólo si está en la segunda fila o mayor se reversa la anterior*/
					if (pos_suger >=0) {
						sugerTabla.rows[pos_suger].className="normal";
					}
					pos_suger = pos_suger + 1;
				}
				sugerTabla.rows[pos_suger].className="sobre";
				var caja = document.getElementById("caja_busqueda");
				caja[0].value = sugerTabla.rows[pos_suger].cells[0].innerHTML;
				return false;
			}
		}
		/* Flecha hacia arriba*/
		else if (keycode == 38) {
			var sugerencia = document.getElementById("suggestions");
			if (sugerencia.style.display != 'none') {
				var sugerTabla = document.getElementById("sugerTabla");
				if (pos_suger>0) {
					/*sólo si está en la penultima fila o menor se reversa la anterior*/
					if (pos_suger<sugerTabla.rows.length && pos_suger<10) {
						sugerTabla.rows[pos_suger].className="normal";
					}
					pos_suger = pos_suger -1;
				}
				sugerTabla.rows[pos_suger].className="sobre";
				var caja = document.getElementById("caja_busqueda");
				caja[0].value = sugerTabla.rows[pos_suger].cells[0].innerHTML;
				return false;
			}
		/*Se presiona <esc> entonces se esconde el pop-up*/
		else if (keycode == 27) {
			setTimeout("$('#suggestions').hide();", 200);
			return false;
		}
		else
			return true;
		}

	}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}

MM_reloadPage(true);
