var parametro = "http://buscador.chileclic.cl/";

/* 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 */

/* 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;
  }

function SendSearch(){
	var fecha = new Date();
	var fjlfin = Math.round(dayjulian(fecha.getDate(),fecha.getMonth(),fecha.getFullYear(),fecha.getHours(),fecha.getMinutes()));
	var query = "";
	var fjlini;
	var occt;

	if (trim(window.document.formDatos.as_q.value) != ""){
		query = query + reno(trim(window.document.formDatos.as_q.value),"+");
	}

	if (trim(window.document.formDatos.as_epq.value) != ""){
	    if (query != ""){
			query = query + " " + '"' + (trim(window.document.formDatos.as_epq.value)) + '"';
		} else {
			query = '"' + (trim(window.document.formDatos.as_epq.value)) + '"';
		}
	}

	if (trim(window.document.formDatos.as_oq.value) != ""){
		if (query != ""){
			query = query + " " + reno(trim(window.document.formDatos.as_oq.value)," OR ");
		} else{
			query = reno(trim(window.document.formDatos.as_oq.value)," OR ");
		}
	}

	if (trim(window.document.formDatos.as_eq.value) != ""){
		if (query != ""){
			query = query + " " + menos(trim(window.document.formDatos.as_eq.value),"-");
		}else{
			query = menos(trim(window.document.formDatos.as_eq.value),"-");
		}
	}

	if (window.document.formDatos.as_filetype.value != ""){
		if (window.document.formDatos.as_ft.value=='i'){
			query = query + " " + "filetype:" + window.document.formDatos.as_filetype.value;	
		} 	else {
			query = query + " " + "-filetype:" + window.document.formDatos.as_filetype.value;
		}
	}

	if (window.document.formDatos.as_qdr.value != "all") {
		switch (window.document.formDatos.as_qdr.value){
		case "d":
			fini = actualizar(1);
			fjlini = Math.round(dayjulian(fini.getDate(),fini.getMonth(),fini.getFullYear(),fini.getHours(),fini.getMinutes()));
			break;
		case "w":
			fini = actualizar(7);
			fjlini = Math.round(dayjulian(fini.getDate(),fini.getMonth(),fini.getFullYear(),fini.getHours(),fini.getMinutes()));
			break;
		case "m":
			fini = actualizar(30);
			fjlini = Math.round(dayjulian(fini.getDate(),fini.getMonth(),fini.getFullYear(),fini.getHours(),fini.getMinutes()));
			break;
		case "y":
			fini = actualizar(365);
			fjlini = Math.round(dayjulian(fini.getDate(),fini.getMonth(),fini.getFullYear(),fini.getHours(),fini.getMinutes()));
			break;
		default:
				break;
		}

		jdate = fjlfin + "-" + fjlini;
		query = query + " " + "daterange:" + jdate;
	}	

	if (window.document.formDatos.as_occt.value != "any") {
		switch (window.document.formDatos.as_occt.value){
			case "title":
				occt = "allintitle:";
				break;
			case "body":
				occt = "allintext:";
				break;
			case "url":
				occt = "allinurl:";
				break;
			case "links":
				occt = "allinlinks:";
				break;
			default:
				break;
		}
		query = occt + query;
	}

	if (window.document.formDatos.as_sitesearch.value != ""){
		if (window.document.formDatos.as_ft.value=='i'){
			query = query + " " + "site:" + window.document.formDatos.as_sitesearch.value;	
		} 	else {
			query = query + " " + "-site:" + window.document.formDatos.as_sitesearch.value;
		}
	}

	//SafeSearch Queda por Revisar
	if (window.document.formDatos.safe.value != "images"){
		safe = 'active';
	}

	/* Ciudades Digitales: Si se agrega o elimina un botón de refinamiento se debe modificar aquí */
	switch (window.document.formDatos.as_reft.value){
			case "a":
				ref = "0";
				break;
			case "e":
				ref = "1";
				break;
			case "t":
				ref = "2";
				break;
			case "m":
				ref = "3";
				break;
			case "c":
				ref = "4";
				break;
			default:
				break;
	}
	
	query = urlencode(query);
		window.location.href = parametro + "buscar.php?consulta=" + query + "&refina=" + ref;
}
function urlencode (str) {  
  return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').  
                                 replace(/\)/g, '%29').replace(/\*/g, '%2A');  
}  
function SendRq(){
	/*var parametro = "http://buscador.chileclic.cl/";*/
    var query;
	if (window.document.formSimilar.as_rq.value != ""){
			query = urlencode("related:" + window.document.formSimilar.as_rq.value);	
	}

   window.location.href= parametro + "buscar.php?consulta="+ query;
}

function SendLq(){
	/*var parametro = "http://buscador.chileclic.cl/";*/
    var query;

	if (window.document.formEnlaces.as_lq.value != ""){

			query = urlencode("link:" + window.document.formEnlaces.as_lq.value);	

	}

	window.location.href= parametro + "buscar.php?consulta="+ query;
}

function trim(cadena){
	for (i=0; i<cadena.length; ){
		if (cadena.charAt(i) == " "){
			cadena=cadena.substring(i+1, cadena.length);
        } else {
                 break;
                }
	}

    for(i=cadena.length-1; i>=0; i=cadena.length-1){
		if (cadena.charAt(i) == " "){
			cadena=cadena.substring(0,i);
		} else {
				 break;
				}
	}
    return cadena;
}

function reno(cadena,simbolo){
	var flag = "";
	for (i=0; i<cadena.length; i++){
		if (cadena[i] == " "){
			flag=flag + simbolo;
		} else {
				flag=flag + cadena[i];
				}		 
	}
	return flag;
}
 
function menos(cadena,simbolo){
    var flag = "";
	for (i=0; i<cadena.length; i++){
	    if (i==0) {flag=simbolo;}
		if (cadena[i] == " "){
			flag=flag + " " + simbolo;
		} else {
				flag=flag + cadena[i];
		}
    }
	return flag;
}

function dayjulian(jdia,jmes,jano,jhh,jmm) {
	MM=eval(jmes)
    DD=eval(jdia)
    YY=eval(jano)
    HR=eval(jhh)
    MN=eval(jmm)
	
    with (Math) {  
      HR = HR + (MN / 60);
      GGG = 1;
      if (YY <= 1585) GGG = 0;
      JD = -1 * floor(7 * (floor((MM + 9) / 12) + YY) / 4);
      S = 1;
      if ((MM - 9)<0) S=-1;

      A = abs(MM - 9);
      J1 = floor(YY + S * floor(A / 7));
      J1 = -1 * floor((floor(J1 / 100) + 1) * 3 / 4);
      JD = JD + floor(275 * MM / 9) + DD + (GGG * J1);
      JD = JD + 1721027 + 2 * GGG + 367 * YY - 0.5;
      JD = JD + (HR / 24);
    }
    return JD;
}

function actualizar(dias){
	milisegundos=parseInt(dias*24*60*60*1000);
	fdate=new Date();
	tiempo=fdate.getTime();
	total=fdate.setTime(parseInt(tiempo-milisegundos));
	return fdate;
}

function avanza_Submit(origen,e){
	  	var keycode;
		if (window.event) 
		{
			keycode = window.event.keyCode;
		}
		else 
			if (e) 
			{
				keycode = e.which;	
			}
			
		
		if (keycode == 13)
   		{
   			SendSearch();
   			return false;
   		}
		else
   			return true;
	  }
function avanza_Submit_Rq(origen,e){
	  	var keycode;
		if (window.event) 
		{
			keycode = window.event.keyCode;
		}
		else 
			if (e) 
			{
				keycode = e.which;	
			}
			
		
		if (keycode == 13)
   		{
   			SendRq();
   			return false;
   		}
		else
   			return true;
	  }
	  
function avanza_Submit_Lq(origen,e){
	  	var keycode;
		if (window.event) 
		{
			keycode = window.event.keyCode;
		}
		else 
			if (e) 
			{
				keycode = e.which;	
			}
			
		
		if (keycode == 13)
   		{
   			SendLq();
   			return false;
   		}
		else
   			return true;
}