var AJAX_SUCCESS         = 0;
var AJAX_INVALIDOBJECT   = 1;
var AJAX_INVALIDCALLBACK = 2;
var AJAX_FAILEDOPEN      = 3;

function Ajax () {
    this.version       = '0.01';
    this.isAsync       = false;
    this.agent         = null;
    this.lastException = '';
    if( typeof XMLHttpRequest != 'undefined' )
        this.agent = new XMLHttpRequest();
    if( this.agent == null ) {
        var axos = new Array(
            'MSXML2.XMLHTTP.4.0',
            'MSXML2.XMLHTTP.3.0',
            'MSXML2.XMLHTTP',
            'Microsoft.XMLHTTP'
        );
        for( var i = 0; this.agent == null && i < axos.length; i++ ) {
            try {
                this.agent = new ActiveXObject(axos[i]);
            } catch(e) {
                this.lastException = e;
                this.agent         = null;
            }
        }
    }
   this.isValid  = callAjaxIsValid;
   this.get      = callAjaxGet;
   this.post     = callAjaxPost;
   this.open     = callAjaxOpen;
   this.request  = callAjaxRequest;
   this.response = callAjaxResponse;
}
function AjaxResponse() {
    this.status     = 0;
    this.statusText = '';
    this.headers    = new Array();
    this.body       = '';
    this.text       = '';
    this.xml        = '';
}
function AjaxRequest() {
    this.method   = 'GET';
    this.url      = '';
    this.headers  = new Array();
    this.body     = null;
    this.callback = null;
}
function callAjaxGet( url, callback, headers ) {
    return this.open( 'GET', url, null, callback, headers );
}
function callAjaxIsValid() {
    return this.agent != null;
}
function callAjaxOpen( method, url, data, callback, headers ) {

    if (this.isValid()) {

        if (!method)  method       = 'GET';
        if (!data)    data         = null;
        if (callback) this.isAsync = true;
        if (this.isAsync) {
            if ( typeof callback != 'function' )
                return AJAX_INVALIDCALLBACK;
            this.agent.onreadystatechange = callback;
        }
        try {
            this.agent.open( method, url, this.isAsync );
        } catch(e) {
            this.lastException = e;
            return AJAX_FAILEDOPEN;
        }
        if ( method == 'POST' ) {
            this.agent.setRequestHeader( 'Connection', 'close' );
            this.agent.setRequestHeader( 'Content-type',
              'application/x-www-form-urlencoded' );
        }
        if ( headers != null ) {
            for ( var header in headers ) {
                this.agent.setRequestHeader( header, headers[header] );
            }
        }

        this.agent.send(data);
        return AJAX_SUCCESS;
    }
    return AJAX_INVALIDOBJECT;
}
function callAjaxPost( url, data, callback, headers ) {
    return this.open( 'POST', url, data, callback, headers );
}
function callAjaxResponse() {
    if ( this.agent.readyState != 4 )
        return null;
    var res = new AjaxResponse();
    res.status      = this.agent.status;
    res.statusText  = typeof this.agent.statusText == 'undefined'
        ? ''
        : this.agent.statusText;
    res.body        = typeof this.agent.responseBody == 'undefined'
        ? ''
        : this.agent.responseBody;
    res.text        = typeof this.agent.responseText == 'undefined'
        ? ''
        : this.agent.responseText;
    res.xml          = this.agent.responseXML == null
        ? ''
        : this.agent.responseXML;
    var string = this.agent.getAllResponseHeaders();
    if (!string) string = '';
    var lines = string.split("\\n");
    for ( var i = 0; i < lines.length; i++ ) {
        var header = lines[i].split(": ");
        if(header.length >= 2) {
            var headername  = header.shift();
            var headervalue = header.join(": ");
            res.headers[headername] = headervalue;
        }
    }
    return res;
}
function callAjaxRequest(req) {
   return this.Open(
       req.method,
       req.url,
       req.body,
       req.callback,
       req.headers
   );
}
function observeField ( field, uri, freq, update, value, param ) {
    var current_value = document.getElementById(field).value;
    if ( value != current_value) {
        var ajax = new Ajax();
        ajax.post(
            uri,
            encodeURIComponent(param) + '=' + encodeURIComponent(current_value),
            function () {
                var res = ajax.response();
                if ( res && res.status == 200 )
                    document.getElementById(update).innerHTML = res.text;
            }
        );
    }
    setTimeout(
        function() {
            observeField( field, uri, freq, update, current_value, param );
        },
        freq * 1000
    );
}
function unserialize(string){
	var trozos = string.split("?");
	trozos = trozos[1].split("&");
	var salida = new Array();
	var i = 0;
        for(i=0;i<trozos.length;i++){
		var v = trozos[i];	
		var partes = v.split("=");
		salida[partes[0]] = partes[1];
	}
	return salida;
}

function serializeForm (form,update) {
    var elements = document.getElementById(form).elements;
    var fields = new Array();
	
    for ( var i = 0; i < elements.length; i++ ) {
		//alert(i);
        var element = elements[i];
	
		
				//alert(i+" <-i - elemento-> "+element.name +" tipo "+ element.type.toLowerCase() + " - ");
	
        switch (element.type.toLowerCase()) {
            case 'hidden':
            case 'password':
	    case 'textarea':
            case 'text':
		mivalue = escape(element.value);
                fields.push( element.name + '=' + mivalue );break;
	    case 'select-multiple': 
		for(j=0 ; j<element.options.length ; j++) 
			if(element.options[j].selected) fields.push(element.name + '=' + element.options[j].value);	
		break;
	    case 'select-one': fields.push(element.name + '=' + element.options[element.selectedIndex].value) ;break;				
            case 'checkbox':
            case 'radio':
                if (element.checked)
                    fields.push(
                        encodeURIComponent(element.name)
                        + '=' +
                        encodeURIComponent(element.value)
                    );
        }
//alert(fields.length);
    }
//alert(fields.join('&'));
	fields.push("ajaxcontrol=1");
	fields.push("destino="+update);
	
    return fields.join('&');
}
function observeForm ( form, uri, freq, update, value ) {
    var current_value = serializeForm(form);
    if ( value != current_value) {
        var ajax = new Ajax();
        ajax.post(
            uri,
            current_value,
            function () {
                var res = ajax.response();
                if ( update && res && res.status == 200 )
                    document.getElementById(update).innerHTML = res.text;
            }
        );
    }
    setTimeout(
        function() {
            observeForm( form, uri, freq, update, current_value );
        },
        freq * 1000
    );
}
/*function submitForm ( form, uri, update, extra ) {
	
    var value = serializeForm(form,update) + extra ;
    var ajax = new Ajax();
    ajax.post(
        uri,
        value,
        function () {
            var res = ajax.response();
            if ( update && res && res.status == 200 )
                document.getElementById(update).innerHTML = res.text;
        }
    );
}*/

function LOGIN ( form, uri, update, extra ) {
	
    var value = serializeForm(form,update) + extra ;
    var ajax = new Ajax();
    ajax.post(
        uri,
        value,
        function () {
            var res = ajax.response();
            if ( update && res && res.status == 200 ){
		//alert(res.text);
	                document.getElementById(update).innerHTML = res.text;
			if(res.text == "ACCESO PERMITIDO") window.location = '/midiariocritico/';
		}
        }
    );
}

function submitForm ( form, uri, update, extra ) {
	var serie = '&' + serializeForm(form,update) + extra;		
	linkTo(uri,update,serie);
	return 1;
}

function submitFormNeutro ( form, uri, extra ) {
	
    var value = serializeForm(form,'neutro') + extra ;
    Action(uri,value);
	 /*   var ajax = new Ajax();
	    //alert(value);
	    ajax.post(
		uri,
		value,
		function () {
		    var res = ajax.response();
		}
	    );*/
}

function Action(uri,value){


	//var destino = $(update);
	value = 'ajaxcontrol=1&destino=neutro' + value;
	var url = uri +'?'+ value;
	var req = new Request.HTML(
		{	
			url:url,
			evalResponse:true,
			onSuccess: function(html) {	

			}
		}
	);		
	req.send();
	return false;
}

function linkTo ( uri, update, value ) {	
	var destino = $(update);
	value = 'ajaxcontrol=1&destino=' + update + value;
	var url = uri +'?'+ value;
	var req = new Request.HTML(
		{	
			url:url,
			evalResponse:true,
			update: destino,
			onSuccess: function(html) {	
				destino.morph({'opacity':[0.5,1]});
			}
		}
	);		
	req.send();

	return false;
}




function linkToLoad (subvista,  value ) {	
	var uri = 'index.php';
    	var update = 'sobre';
    	var destino = $('sobre');
    	var movil = $('box');
	movil.morph({'top':['-500px','10px']});
	destino.setStyle('opacity','1');
	destino.setStyle('display','block');
    	value = 'ajaxcontrol=1&destino=' + update +'&subvista=' + subvista + value;
	var url = uri +'?'+ value;
	var req = new Request.HTML(
		{	
			url:url,
			evalResponse:true,
			onSuccess: function(html) {	
				movil.set('html','prueba');
				movil.adopt(html);
			}
		}
	);		
	req.send();
	return false;
}


function closeLoad() {
	var destino = $('sobre');
    	var movil = $('box');
	movil.morph({'top':'-500px'});
        destino.morph({opacity:0});
	return false;
}


function linkToLoad2 (subvista,  value ) {	
    var ajax = new Ajax();
    var uri = 'index.php';
    var update = 'sobre2';
    document.getElementById('sobre').style.display = 'block'
    value = 'ajaxcontrol=1&destino=' + update +'&subvista=' + subvista + value;
    ajax.post(
        uri,
        value,
        function () {
            var res = ajax.response();
            
            document.getElementById(update).innerHTML = "";
            if ( update && res && res.status == 200 ){
				//alert(res.text + " MALAMENTE");
                document.getElementById(update).innerHTML = res.text;
			}

        }
    );
}

function getLinkTo ( uri, update ) {
    var ajax = new Ajax();
    ajax.get(
        uri,
        function () {
			var txto="";
			var txt2="";		
            var res = ajax.response();			
            if ( update && res && res.status == 200 )
				//txto=unescape(ajax.responseText);
			    txto=unescape(res.text);
				txt2=txto.replace(/\+/gi," ");
                document.getElementById(update).innerHTML = txto;
		//else	 		alert("AJA!!!");
        }
    );
}

function getAjax_check ( uri, update, campo_check, campo_re ) {
    var ajax = new Ajax();
    ajax.get(
        uri,
        function () {
            var res = ajax.response();
            if ( update && res && res.status == 200 )
				if (res.text == 1) // Existe un usuario ya igual
				{
	                document.getElementById(update).innerHTML = "<font class=subbloque_total>Nombre de usuario '"+document.getElementById(campo_check).value+"' ya utilizado. Busque otro nombre de usuario</font> ";						
					document.getElementById(campo_check).value="";
					document.getElementById(campo_re).value=1;
				}
				else
				{
	              //  document.getElementById(update).innerHTML = "<font color='#000000' face>Nombre de Usuario '"+document.getElementById(campo_check).value+"' válido</font> ";	
	                document.getElementById(update).innerHTML = "";					  
					document.getElementById(campo_re).value=0;						
				}
				
//		else	 		alert("AJA!!!");
        }
    );
}

function getParentLinkTo ( uri, update ) {
    var ajax = new Ajax();
    ajax.get(
        uri,
        function () {
            var res = ajax.response();
            if ( update && res && res.status == 200 )
				{
  	              parent.document.getElementById(update).innerHTML = res.text;
				}
		//else	 		alert("AJA!!!");
        }
    );
}
function getOpenerLinkTo ( uri, update ) {
    var ajax = new Ajax();
    ajax.get(
        uri,
        function () {
            var res = ajax.response();
            if ( update && res && res.status == 200 )
				{
  	              window.opener.document.getElementById(update).innerHTML = res.text;
				}
		//else	 		alert("AJA!!!");
        }
    );
}

function linkField ( field, uri, update, param ) {
    var value = document.getElementById(field).value;
    var ajax = new Ajax();
    ajax.post(
        uri,
        encodeURIComponent(param) + '=' + encodeURIComponent(value),
        function () {
            var res = ajax.response();
            if ( update && res && res.status == 200 )
                document.getElementById(update).innerHTML = res.text;
        }
    );
}

function Insertar_Texto(texto,destino)
{
	document.getElementById(destino).innerHTML = texto;		
}
