//declaro mi objeto httpdRequest 
var http;

/* 
Este es nuestro manejador de eventos, lo que hace despues de resivir la info en el metodo sendQueryString 

Estado del Objeto: 
0 = uninitialized 
1 = loading 
2 = loaded 
3 = interactive 
4 = complete 
*/


/* 
aki es donde mandas el resquest del server de la pagina 

Normalmenteo uno querie que el servidor procese la pagina enviada por XmlHttpRquest con objetos diferentes a lo normales. 
Esto se hace reconociendo POST Y GET 

Este script es asincronico -- sigue corriendo despues de aver enviado un request 

lo de send(null) es lo normal todavia no se mas que esto asi que vamos por paso ^_^ 
*/


//funcio que fa una peticio (utilitza http (si nomes fai una pet));
function sendQuerystring(dir, func) 
{ 
	http = getXmlHttpObject();
	//abre la pagina
  http.open("GET", dir, true);
	//alert("HOLA ajax");
  //mando la información obtenida a la funcion handleHttpResponse
  //http.onreadystatechange = handleHttpResponse;
  http.onreadystatechange = func;
  //send nada
  http.send(null);
  
} 

function sendQuerystring_post(dir, vars, func) 
{ 
	http = getXmlHttpObject();
  //mando la información obtenida a la funcion handleHttpResponse
  //http.onreadystatechange = handleHttpResponse;
  
  http.onreadystatechange = func;
	//abre la pagina
	
  http.open("POST", dir, true);
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  //send variables
  //http.send("hola=1234");
  http.send(vars);
  
} 


//funcio que fa una peticio (utilitza http_obj (si fai més de una pet));
function sendPet(dir, func, http_obj) 
{ 
	//alert(dir);
	
	http_obj = getXmlHttpObject();
	//abre la pagina
  http_obj.open("GET", dir, true);
  //mando la información obtenida a la funcion handleHttpResponse
  //http.onreadystatechange = handleHttpResponse;
  http_obj.onreadystatechange = func;
  //send nada
  http_obj.send(null);
  
} 


/* 
esta es la funcion principal, no tocar solo copy y paste y listo ^_^ 
*/
 
function getXmlHttpObject() 
{  
    //alert("getXmlHttpObject");
    var xmlhttp;
		
    /*@cc_on 
    @if (@_jscript_version >= 5) 
    try 
    { 
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
    } 
    catch (e) 
    { 
    
    try{ 
    		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    catch (e){ 
    		xmlhttp = false; 
    } 
    } 
    @else 
    xmlhttp = false; 
    @end @*/

    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try{
            xmlhttp = new XMLHttpRequest();
        }
        catch (e){
            xmlhttp = false;
        } 
    }
    return xmlhttp; 
}

//functio que genera el xorro de variables pel GET
function get_query(form_name){
		var form = document.getElementById(form_name);
		query = "?" + form.elements[0].id + "=" + codif_query(form.elements[0].value);
		for(var i = 1; i < form.elements.length; i++){
			query = query + "&" + form.elements[i].id + "=" + codif_query(form.elements[i].value);
		}
		//alert(query);
		//query = myurl.encode(query);
		//query = Base64.encode(query);
		return query;
	
}

function get_query_buscador(form_name){
		var form = document.getElementById(form_name);
		
		if (form.radio_compra.checked) {
			form.operacion_f.value = "C";
		} else if (form.radio_alquiler.checked) {
				form.operacion_f.value = "A";
		}
		
		//	recogo el valor de los campos, lo codifico y lo asigno a la variable que toca.
		form.operacion_f.value = codif_query(form.operacion_f.value);
		form.ref_f.value = codif_query(form.referencia_field.value);
		form.combo_tipo_f.value = codif_query(form.tipo_field.options[form.tipo_field.selectedIndex].value);
		form.combo_zona_f.value = codif_query(form.zona_field.options[form.zona_field.selectedIndex].value);
		form.poblacion_f.value = codif_query(form.poblacion_field.value);
		form.smin_f.value = codif_query(form.superficie_min_field.options[form.superficie_min_field.selectedIndex].value);
		form.smax_f.value = codif_query(form.superficie_max_field.options[form.superficie_max_field.selectedIndex].value);
		form.offset_pag.value = codif_query(form.offset_pag.value);
		
		query = "?" + form.operacion_f.id + "=" + form.operacion_f.value;
		query = query + "&" + form.ref_f.id + "=" + form.ref_f.value;
		query = query + "&" + form.combo_tipo_f.id + "=" + form.combo_tipo_f.value;
		query = query + "&" + form.combo_zona_f.id + "=" + form.combo_zona_f.value		
		query = query + "&" + form.poblacion_f.id + "=" + form.poblacion_f.value;
		query = query + "&" + form.smin_f.id + "=" + form.smin_f.value;
		query = query + "&" + form.smax_f.id + "=" + form.smax_f.value;
		query = query + "&" + form.smax_f.id + "=" + form.smax_f.value;
		query = query + "&" + form.offset_pag.id + "=" + form.offset_pag.value;
		
		//alert(query);
		//query = myurl.encode(query);
		//query = Base64.encode(query);
		return query;
	
}

function get_query_post(form_name){
		var form = document.getElementById(form_name);
		query = "" + form.elements[0].id + "=" + codif_query(form.elements[0].value);
		for(var i = 1; i < form.elements.length; i++){
			query = query + "&" + form.elements[i].id + "=" + codif_query(form.elements[i].value);
		}
		//alert(query);
		//query = myurl.encode(query);
		//query = Base64.encode(query);
		return query;
	
}

//funció que permet enviar%
function codif_query(str){
	if(str != undefined){
		str = replace_all(str, "'", "___com___");
		str = replace_all(str, '"', "___com2___");
		str = Base64.encode(str);
		
		str = replace_all(str, "%", "___per___");
		str = str2html(str);
		str = replace_all(str, "&", "___amp___");
		
		str = replace_all(str, "+", "%2B");
		str = replace_all(str, "/", "%2F");
		
		return str;
	}
}

function replace_all(varStr,varText,varBy){
	var strTmp = varStr;
	
	while(strTmp.indexOf(varText) >= 0) {
		strTmp = strTmp.replace(varText,varBy);
	}
	
	return strTmp;
}

function str2html(str){
	if(str != ""){
		str = replace_all(str,"&","&amp;");
		str = replace_all(str,"¿","&iquest;");
		str = replace_all(str,"¡","&iexcl;");
		str = replace_all(str, "ª", "&ordf;");
		str = replace_all(str, "º", "&ordm;");
		str = replace_all(str,'"','&quot;');
		str = replace_all(str,'\n','<br>');
		//str = replaceAll(str,'\r','<br>');
		
		/*
		str = replace_all(str, "ç", "&ccedil;");
		str = replace_all(str, "Ç", "&Ccedil;");
		str = replace_all(str, "ñ", "&ntilde;");
		str = replace_all(str, "Ñ", "&Ntilde;");
		
		str = replace_all(str, "á", "&aacute;");
		str = replace_all(str, "é", "&eacute;");
		str = replace_all(str, "í", "&iacute;");
		str = replace_all(str, "ó", "&oacute;");
		str = replace_all(str, "ú", "&uacute;");
		str = replace_all(str, "Á", "&Aacute;");
		str = replace_all(str, "É", "&Eacute;");
		str = replace_all(str, "Í", "&Iacute;");
		str = replace_all(str, "Ó", "&Oacute;");
		str = replace_all(str, "Ú", "&Uacute;");
		str = replace_all(str, "à", "&agrave;");
		str = replace_all(str, "è", "&egrave;");
		str = replace_all(str, "ò", "&ograve;");
		str = replace_all(str, "À", "&Agrave;");
		str = replace_all(str, "È", "&Egrave;");
		str = replace_all(str, "Ò", "&Ograve;");
		str = replace_all(str, "ü", "&uuml;");
		str = replace_all(str, "Ü", "&Uuml;");
		str = replace_all(str, "ï", "&iuml;");
		str = replace_all(str, "Ï", "&Iuml;"); 
		*/

	}
	return str;
}


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}