//Basado en:
//HTMLHttpRequest v1.0 beta2 (c) 2001-2005 Angus Turnbull, TwinHelix Designs http://www.twinhelix.com
//Licensed under the CC-GNU LGPL, version 2.1 or later: http://creativecommons.org/licenses/LGPL/2.1/


// Some common event API code I use. Syntax:
//   addEvent(object_reference, 'name_of_event', function_reference, legacy);
// 'name_of_event' is without the 'on' prefix, e.g. 'load', 'click' or 'mouseover'.
// 'legacy' disables addEventListener if true.
// You can add multiple events to one object, and in MSIE all are removed onunload.
 
var aeOL = [];
function addEvent(o, n, f, l)
{
 var a = 'addEventListener', h = 'on'+n, b = '', s = '';
 if (o[a] && !l) return o[a](n, f, false);
 o._c |= 0;
 if (o[h])
 {
  b = '_f' + o._c++;
  o[b] = o[h];
 }
 s = '_f' + o._c++;
 o[s] = f;
 o[h] = function(e)
 {
  e = e || window.event;
  var r = true;
  if(o[b] != null){
   if (b) r = o[b](e) != false && r;
   r = o[s](e) != false && r;
  }
  return r;
 };
 aeOL[aeOL.length] = { o: o, h: h };
};
addEvent(window, 'unload', function() {
 for (var i = 0; i < aeOL.length; i++) with (aeOL[i])
 {
  o[h] = null;
  for (var c = 0; o['_f' + c]; c++) o['_f' + c] = null;
 }
});

function cancelEvent(e, c)
{
 e.returnValue = false;
 if (e.preventDefault) e.preventDefault();
 if (c)
 {
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
 }
};

// SYNTAX INSTRUCTIONS for HTMLHttpRequest:
//
// function callback_function(DOMDocument) { /* Parse DOM document here */ }
//
// var objectName = new HTMLHttpRequest('objectName', callback_function);
//
// Create an instance of an HTMLHttpRequest object, and pass its own name as a string,
// a reference to a callback function, and a pathname to a blank HTML document.
// The callback function will be called on load/submit completion with parameters:
//  1) A reference to the loaded DOM document (which you may then parse).
//  2) The requested URI.
// NOTE: All requested documents must reside on the same domain as this document!
//
// Available methods are:
//
// objectName.load('file.html');
//
// This will issue a GET request to the server to return a named file.
//
// objectName.submit(form_reference, event_object);
//
// This will capture a form's submission and redirect it to a background POST or GET
// request, respecting the form's 'method' attribute and its 'action' URI.
// Pass it a reference to the form's DOM node, and the event object from the submittal.
// Note that the form must be *already* in the process of submission when this is called.
// It is therefore suggested that you call it from within an ONSUBMIT handler on a form.

var threads = [];
function HTMLHttpRequest(callback, oParams) { with (this)
{
 window._iObjCount |= 0;
 this.Tipo = 0;
 this.numero = _iObjCount;
 this.myName = 'Objeto_' + window._iObjCount++;
 threads[_iObjCount-1] = this;
 this.callback = callback;
 this.params = oParams;
 
 // 'xmlhttp': Our preferred request object. Accepted wherever HTML is sold.
 this.xmlhttp = null;
 // 'iframe' is our fallback: a reference to a dynamically created IFRAME buffer.
 this.iframe = null;
 window._ifr_buf_count |= 0;
 this.iframeID = 'iframebuffer' + window._ifr_buf_count++;
 // A loading flag, set to the requested URI when loading.
 this.loadingURI = '';

 // Attempt to init an XMLHttpRequest object where supported.
 // Note: MSIE7 is best with the IFRAME method, so exclude IE here.
 if (window.XMLHttpRequest && !window.ActiveXObject) {
 	 xmlhttp = new XMLHttpRequest();
 }

 if (window.ActiveXObject)
 { 
  try{
  	//alert('Microsoft.XMLHTTP');
    //xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp = new ActiveXObject("MSXML2.ServerXMLHTTP");
  }
  catch(err)
  {
    xmlhttp = null; //No tiene acceso a crear activex. Voy a la ultima que me queda... el iframe.
  }
 }

 if (!xmlhttp)
 {
  // In MSIE or browsers with no XMLHttpRequest support: fallback to IFRAMEs buffers.
  // I'm using IFRAMEs in MSIE due to XMLHTTP not parsing text/html to a DOM.
  // Also used in IE5/Mac, Opera 7.x, Safari <1.2, some Konqueror versions, etc.
  if (document.createElement && document.documentElement &&
   (window.opera || navigator.userAgent.indexOf('MSIE 5.0') == -1))
  {
   var ifr = document.createElement('iframe');
   ifr.setAttribute('id', iframeID);
   ifr.setAttribute('name', iframeID);
   // Hide with visibility instead of display to fix Safari bug.
   ifr.style.visibility = 'hidden';
   ifr.style.position = 'absolute';
   ifr.style.width = ifr.style.height = ifr.borderWidth = '0px';
   ifr.src = 'javascript:;';
   iframe = document.getElementsByTagName('body')[0].appendChild(ifr);

  }
  else if (document.body && document.body.insertAdjacentHTML)
  {
   // IE5.0 doesn't like createElement'd frames (won't script them) and IE4 just plain
   // doesn't support it. Luckily, this will fix them both:
   document.body.insertAdjacentHTML('beforeEnd', '<iframe name="' + iframeID +
    '" id="' + iframeID + '" style="display: none"></iframe>');
  }
  // This helps most IE versions regardless of the creation method:
  if (window.frames && window.frames[iframeID]) iframe = window.frames[iframeID];
  iframe.name = iframeID;
 }
 return this;
}};


HTMLHttpRequest.prototype.xmlhttpSend = function(uri, formStr) { with (this)
{
 // Use XMLHttpRequest to asynchronously open a URI, and optionally POST a provided
 // form string if any (otherwise, performs a GET).

 xmlhttp.open(formStr ? 'POST' : 'GET', uri, true);
 var self = this;
 xmlhttp.onreadystatechange = function() {  
  if (xmlhttp.readyState==4 && xmlhttp.responseText)
  {
   var sDoc;
   
   if (self.Tipo==0)
   {
     sDoc = xmlhttp.responseText
   }
   else
   {
     sDoc = xmlhttp.responseXML
   }
   // If you are getting an error where 'doc' is null in your own code, try changing
   // the MIME type returned by the server: setting it to text/xml usually works well!
   if (callback) callback(sDoc, self.params);
   loadingURI = '';
  }
 };
 
 if (formStr && xmlhttp.setRequestHeader)
  xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
  //alert(xmlhttp.class);
  //xmlhttp.overrideMimeType('text/html; charset=iso-8859-1');
 xmlhttp.send(formStr);
 loadingURI = uri;
 return true;
}};


HTMLHttpRequest.prototype.iframeSend = function(uri, formRef) { with (this)
{
 // Routes a request through our hidden IFRAME. Pass a URI, and optionally a
 // reference to a submitting form. Requires proprietary 'readyState' property.

 if (!document.readyState) return false;

 // Opera fix: force the frame to render before setting it as a target.
 if (document.getElementById) var o = document.getElementById(iframeID).offsetWidth;

 // Either route the form submission to the IFRAME (easy!)...
 if (formRef) formRef.setAttribute('target', iframeID);
 else
 {
  // ...or load the provided URI in the IFRAME, checking for browser bugs:
  // 1) Safari only works well using 'document.location'.
  // 2) Opera needs the 'src' explicitly set!
  // 3) Konqueror 3.1 seems to think ifrDoc's location = window.location, so watch that too.
  var ifrDoc = iframe.contentDocument || iframe.document;

  if (!window.opera && ifrDoc.location &&
   ifrDoc.location.href != location.href) 
   {ifrDoc.location.href= uri;
    //ifrDoc.location.replace(uri);
    
    //alert(ifrDoc.location.);
  }
  else iframe.src = uri;
 }

 // Either way, set the loading flag and start the readyState checking loop.
 // Opera likes a longer initial timeout with multiple frames running...
 loadingURI = uri;
 setTimeout('threads[' + this.numero + '].iframeCheck()', (window.opera ? 250 : 100)); 
 return true;
}};

HTMLHttpRequest.prototype.iframeCheck = function() { with (this)
{
 // Called after a timeout, periodically calls itself until the load is complete.
 // Get a reference to the loaded document, using either W3 contentDocument or IE's DOM.
 doc = iframe.contentDocument || iframe.document;  

 // Check the IFRAME's .readyState property and callback() if load complete.
 // IE4 only seems to advance to 'interactive' so let it proceed from there.
 var il = iframe.location, dr = doc.readyState;
 //if ((il && il.href ? il.href.match(loadingURI) : 1) && (dr == 'complete' || (!document.getElementById && dr == 'interactive')))
 if ((il && il.href ? il.href.match(loadingURI.replace("\?", "\\?")) : 1) && (dr == 'complete' || (!document.getElementById && dr == 'interactive')))
 {    
   if (this.Tipo==0)
   {
    //if (callback) callback( doc.body.innerText, this.params);
    
    if (callback) 
      callback( (doc.innerHTML || (doc.body ? doc.body.innerHTML : '')), this.params);
   }
   else
   {
    if (callback) callback((doc.documentElement || doc), this.params);
//      if (callback) callback(cbDoc, (cbDoc.innerHTML || (cbDoc.body ? cbDoc.body.innerHTML : '')), loadingURI);
   }
   var oIframeBuffer = document.getElementById(this.iframeID);
   oIframeBuffer.parentNode.removeChild( oIframeBuffer );

  loadingURI = '';
 }
 else
  {
     setTimeout('threads[' + this.numero + '].iframeCheck()', 150);
  }
}};


// *** PUBLIC METHODS ***

HTMLHttpRequest.prototype.load = function(uri) { with (this)
{
 // Call with a URI to load a plain text document.
 this.Tipo= 0;
 if (!uri || (!xmlhttp && !iframe)) return false;
 // Route the GET through an available transport layer.
 if (xmlhttp) return xmlhttpSend(uri, '');
 else if (iframe) return iframeSend(uri, null);
 else return false;
}};


HTMLHttpRequest.prototype.loadXML = function(uri) { with (this)
{
 // Call with a URI to load a plain text document.
 this.Tipo= 1;
 if (!uri || (!xmlhttp && !iframe)) return false;
 // Route the GET through an available transport layer.
 if (xmlhttp) return xmlhttpSend(uri, '');
 else if (iframe) return iframeSend(uri, null);
 else return false;
}};

function cargarComboXML(sCombo, sItem, sNombre, sValor, iValorSeleccionado, oXml, bAccionGenerica, sTextoGenerico, sValorGenerico) 
{ 
 if(sCombo!='' && document.getElementById(sCombo)) 
 {
  var oCombo = document.getElementById(sCombo);
  oCombo.length = 0;
  oCombo.selectedIndex = 0;
  var oNodos = oXml.getElementsByTagName(sItem);  
  var x=0;  

  for(x = 0; x<oNodos.length; x++ )
  {
   var oNodo = oNodos[x];
   //cargo el combo.
   var oItem = document.createElement("option");
   oItem.text = oNodo.getAttribute(sNombre);
   oItem.value = parseInt(oNodo.getAttribute(sValor));
   
   //oCombo.options[x] = oItem;
   oCombo.options.add(oItem);
   //selecciono opcion.
   if ((oItem.value == iValorSeleccionado) || (oItem.value==0 && x==0))
   {
    oCombo.selectedIndex = x;
   }
  }
  if (bAccionGenerica)
  {
   var oItem = document.createElement("option");
   oItem.text = sTextoGenerico;
   oItem.value = sValorGenerico;
   oCombo.options.add(oItem,0);
   if(!iValorSeleccionado)
   {
    oCombo.selectedIndex= 0;
   }
  }  
 }
}

function ClearDropDown(sCombo, bAccionGenerica, sTextoGenerico, sValorGenerico)
{
 if(sCombo!='' && document.getElementById(sCombo)) 
 {
  var oCombo = document.getElementById(sCombo);
  oCombo.length = 0;
  oCombo.selectedIndex = 0;
  if (bAccionGenerica)
  {
   var oItem = document.createElement("option");
   oItem.text = sTextoGenerico;
   oItem.value = sValorGenerico;
   oCombo.options.add(oItem,0);
  }
 }
}

function isArray(obj){return(typeof(obj.length)=="undefined")?false:true;}

function SeleccionarItem(sElemento, valor)
{
  var oElementos = document.getElementsByName(sElemento);
  for(var i=0;i<oElementos.length;i++)
  {
   var oElemento = oElementos[i];
   if(isArray(oElemento)&&(typeof(oElemento.type)=="undefined"))
   {
     for(var j=0;j<oElemento.length;j++)
     {
      setValorInput(oElemento[i],valor);
     }
   }
   else
   {
     setValorInput(oElemento,valor);
   }
  }
}

function setValorInput(obj,valor) {
	switch(obj.type){
		case 'radio': 
		case 'checkbox':
		  if(obj.value==valor)
		  {
		    obj.checked=true;
		    return true;
		  }
		  else
		  {
		    obj.checked=false;
		    return false;
		  }
		case 'text':
		case 'hidden':
		case 'textarea':
		case 'password':
		  obj.value=valor;
		  return true;
		case 'select-one':
		case 'select-multiple':
			var o=obj.options;
			for(var i=0;i<o.length;i++)
		  {
				if(o[i].value==valor)
		    {o[i].selected=true;}
				else
		    {o[i].selected=false;}
		  }
			return true;
		}
	return false;
	}
	
String.prototype.trim = function () { 
 return this.replace(/^\s+|\s+$/g, ''); 
}


function tieneActiveX()
{
 var o = null;
 if (window.ActiveXObject)
 { 
  try{
    //o = new ActiveXObject("Microsoft.XMLHTTP");
	o = new ActiveXObject("MSXML2.ServerXMLHTTP");
  }
  catch(err)
  {
    o = null; //No tiene acceso a crear activex. Voy a la ultima que me queda... el iframe.
  }
 }
 return (o==null?false:true);
 
}