/**

	Título..: VeryTinyAJAX 0.3b, Wrapper JavaScript simple a funciones XMLHTTP para AJAX
  Licencia: GPL (http://www.gnu.org/licenses/gpl.txt)
	Autores.: Pablo Rodríguez Rey (mr.xkr -en- inertinc -punto- org)
	          http://mr.xkr.inertinc.org/
            Javier Gil Motos (cucaracha -en- inertinc -punto- org)
            http://cucaracha.inertinc.org/

	Agradecimientos a Cucaracha, por darme interés en el desarrollo de webs usando
	AJAX y proveerme del ejemplo básico con el que está desarrollada esta librería.

*/


// declarar el objeto XML-HTTP global
var http;

// constantes para httpRequest
var hGET=0;
var hPOST=1;

// funciones auxiliares generales
function gid(id) { return(document.getElementById(id)); }
function gescape(torg) {
	var d=""+torg;
	try { var d=d.replace(/\?/gi,"%3F"); } catch(e) {}
	try { var d=d.replace(/&/gi,"%26"); } catch(e) {}
	try { var d=d.replace(/\+/gi,"%2B"); } catch(e) {}
	try { var d=d.replace(/ /gi,"+"); } catch(e) {}
	return(d);
}

// información de versión
function httpVersion() { return("VeryTinyAJAX/0.3b"); }

// crea el objeto XML-HTTP
function httpObject() {
	var xmlhttp;
	// comprobar que el navegador soporta XMLHttpRequest
	try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
	catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
	catch (e) { try { xmlhttp = new XMLHttpRequest(); }
	catch (e) { xmlhttp = false; } } }
	return(xmlhttp);
}

// estado de la petición
function httpState() {
	try { return(http.readyState); }
	catch (e) { return(5); }
}

// cadena de estado de la petición
function httpStateString() {
	try { var rs=http.readyState; }
	catch (e) { var rs=5; }
	switch (rs) {
	case 0: return("Uninitialized")
	case 1: return("Loading");
	case 2: return("Loaded");
	case 3: return("Interactive");
	case 4: return("Complete");
	case 5: return("Server Crashed");
	}
}

// Indicar si se ha completado la operación
function httpComplete() {
	if (http.readyState==4) return(true);
	else return(false);
}

// Devolver los datos recibidos
function httpData() {
	return(http.responseText);
}

// Devolver los datos recibidos en formato documento XML
function httpXML() {
	return(http.responseXML);
}

// Devolver el estado del servidor
// Si se detecta error, el servidor no estará disponible
function httpStatus() {
	try { return(http.status); }
	catch(e) { return(0); }
}

// Comprobar que la respuesta del servidor es la 200 (HTTP OK)
function httpError() {
	if (http.readyState==4) {
		try { var ok=(http.status!=200); }
		catch(e) { return(true); }
		return(ok);
	}
}

// Muestra un mensaje de error dependiendo del tipo de error encontrado
function httpErrorShow() {
	if (httpError()) {
		if (httpStatus()) alert("Se ha encontrado el error "+httpStatus()+" en el servidor.");
		else alert("El servidor no responde a la petición!\nPruebe dentro de unos instantes.");
	}
}

// Realizar un envío de datos http
function httpSend(method, url, data, eventfunction) {
	var sdata=(data?data:"");
	var async=(eventfunction?true:false);
	http=httpObject();
	switch (method) {
	case 0: http.open("GET",url+"?"+sdata,async); sdata=null; break;
	case 1: http.open("POST",url,async); break;
	default: return(false);
	}
	if (async) http.onreadystatechange=eventfunction;
	http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=ISO-8859-1"');
	http.send(sdata);
	return(true);
}


// Devuelve todos los campos y datos
// de un formulario en forma campo1=dato1&campo2=dato2&...
function httpFormFields(formObject) {
	var fields="";
	for (i=0;i<formObject.length;i++) {
		if (!formObject[i].name) continue;
		if (formObject[i].type=="radio" && !formObject[i].checked) continue;
		fields+=(i>0?"&":"")+formObject[i].name+"="+gescape(httpGetObjectValue(formObject[i]));
	}
	return(fields);
}

// Habilitar o deshabilitar la posibilidad de introducción
// o modificación de datos de un formulario completo.
function httpFormFieldsEnabled(formObject,isEnabled) {
	for (x=0;x<formObject.length;x++) {
		try { formObject[x].disabled=isEnabled; }
		catch(e) {}
	}
}

// Devuelve todos los campos y datos de un lista de identificadores
// tipo id1,id2,id3 en forma id1=dato1&id2=dato2&...
function httpGetFields(fieldNames) {
	var fn=fieldNames.split(",");
	var fields="";
	var formObject;
	for (i=0;i<fn.length;i++) {
		formObject=gid(fn[i]);
		if (!formObject) continue;
		if (formObject.type=="radio" && !formObject.checked) continue;
		fields+=(i>0?"&":"")+fn[i]+"="+gescape(httpGetObjectValue(formObject));
	}
	return(fields);
}

// Devuelve un valor de un campo
function httpGetObjectValue(formObject) {
	switch (formObject.type) {
	case "checkbox": return(formObject.checked?"1":"0");
	case "radio": case "button": case "select-one": case "text": case "textarea": default: return(formObject.value);
	}
}

// Devuelve un objeto con el número de variables
// creadas con la función aset(nombre,valor,es_array);
function aget(fullData) {
	var d=fullData;
	var o=new Object();
	var n=0;
	var p0,p1,p2,isa;
	while (true) {
		try {
			p0=d.indexOf("="); if (!p0) break;
			p1=d.indexOf("("); if (!p1) break;
			p2=d.indexOf(")"); if (!p2) break;
			isa=d.substring(p2+1,p2+2); if (!isa) break;
			isa=(isa=="$"?true:false);
			name=d.substring(0,p1); if (!name) break;
			plength=parseInt(d.substring(p1+1,p2));
			data=d.substring(p0+1,p0+plength+1);
			if (!isa) eval("o."+name+"=data;");
			else eval("o."+name+"="+data+";");
			d=d.substring(p0+plength+2);
		} catch(e) {
			return(false);
		}
	}
	return(o);
}




/*

		PHPSON, based on JSON.js
    2007-02-18

    Public Domain

    This file adds these methods to JavaScript:

        array.aput()
        boolean.aput()
        date.aput()
        number.aput()
        object.aput()
        string.aput()
            These methods produce a PHPSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a aput method to any date object to get a different
            representation.

        string.parsePHPSON(filter)
            This method parses a PHPSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parsePHPSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2008.
*/

// Augment the basic prototypes if they have not already been augmented.

if (!Object.prototype.aput) {

    Array.prototype.aput = function () {
        var a = ['Array(\n'],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            i,          // Loop counter.
            l = this.length,
            v;          // The value to be stringified.

        function p(s) {

// p accumulates text fragments in an array. It inserts a comma before all
// except the first fragment.

            if (b) {
                a.push(',');
            }
            a.push(s);
            b = true;
        }

// For each value in this array...

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {

// Values without a PHPSON representation are ignored.

            case 'function':
            case 'unknown':
                break;

            case 'undefined':
								p("null");
                break;

// Serialize a JavaScript object value. Ignore objects thats lack the
// aput method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

            case 'object':
                if (v) {
                    if (typeof v.aput === 'function') p(v.aput());
                } else {
                    p("null");
                }
                break;

// Otherwise, serialize the value.

            default:
                p(v.aput());
            }
        }

// Join all of the fragments together and return.

        a.push(')\n');
        return a.join('');
    };


    Boolean.prototype.aput = function () {
        return String(this);
    };


    Date.prototype.aput = function () {

				// Ultimately, this method will be equivalent to the date.toISOString method.

        function f(n) {
						// Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getFullYear() + '-' +
                f(this.getMonth() + 1) + '-' +
                f(this.getDate()) + 'T' +
                f(this.getHours()) + ':' +
                f(this.getMinutes()) + ':' +
                f(this.getSeconds()) + '"';
    };


    Number.prototype.aput = function () {
				// PHPSON numbers must be finite. Encode non-finite numbers as null.
        return isFinite(this) ? String(this) : "null";
    };


    Object.prototype.aput = function () {
        var a = ['Array('],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            k,          // The current key.
            v;          // The current value.

        function p(s) {
						// p accumulates text fragment pairs in an array. It inserts a comma before all
						// except the first fragment pair.
            if (b) {
                a.push(',\n');
            }
            a.push(k.aput(), '=>', s);
            b = true;
        }

				// Iterate through all of the keys in the object, ignoring the proto chain.
        for (k in this) {
            if (this.hasOwnProperty(k)) {
                v = this[k];
                switch (typeof v) {

								// Values without a PHPSON representation are ignored.
                case 'undefined':
                case 'function':
                case 'unknown':
                    break;

								// Serialize a JavaScript object value. Ignore objects that lack the
								// aput method. Due to a specification error in ECMAScript,
								// typeof null is 'object', so watch out for that case.
                case 'object':
                    if (v) {
                        if (typeof v.aput === 'function') p(v.aput());
                    } else {
                        p("null");
                    }
                    break;
                default:
                    p(v.aput());
                }
            }
        }

				// Join all of the fragments together and return.
        a.push(')\n'); // fin de array ***
        return a.join('');
    };


    (function (s) {

				// Augment String.prototype. We do this in an immediate anonymous function to
				// avoid defining global variables.

				// m is a table of character substitutions.
        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };
	
        s.parsePHPSON = function (filter) {

						// Parsing happens in three stages. In the first stage, we run the text against
						// a regular expression which looks for non-PHPSON characters. We are especially
						// concerned with '()' and 'new' because they can cause invocation, and '='
						// because it can cause mutation. But just to be safe, we will reject all
						// unexpected characters.
            try {
                if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
                        test(this)) {

										// In the second stage we use the eval function to compile the text into a
										// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
										// in JavaScript: it can begin a block or an object literal. We wrap the text
										// in parens to eliminate the ambiguity.
                    var j = eval('(' + this + ')');

										// In the optional third stage, we recursively walk the new structure, passing
										// each name/value pair to a filter function for possible transformation.
                    if (typeof filter === 'function') {

                        function walk(k, v) {
                            if (v && typeof v === 'object') {
                                for (var i in v) {
                                    if (v.hasOwnProperty(i)) v[i]=walk(i, v[i]);
                                }
                            }
                            return filter(k, v);
                        }

                        walk('', j);
                    }
                    return j;
                }
            } catch (e) {

							// Fall through if the regexp test fails.

            }
            throw new SyntaxError("parsePHPSON");
        };


        s.aput = function () {

						// If the string contains no control characters, no quote characters, and no
						// backslash characters, then we can simply slap some quotes around it.
						// Otherwise we must also replace the offending characters with safe
						// sequences.
            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                    var c = m[b];
                    if (c) {
                        return c;
                    }
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}
