//he probado a comprimirlo con con http://alex.dojotoolkit.org/shrinksafe/ pero da casques
//esta libreria antes se llamaba util.js y es necesaria para utilizar el tema de ajax de una forma mas cómoda

var util = {

  shouldDebug: false,

  // Note: Will fail in pathological cases (where the members contain
  // strings similar to describe() result).
  membersEqual: function(array1, array2) {
    return util.describe(array1)==util.describe(array2);
  },

  describe: function(obj) {
    if (obj==null) { return null; }
    switch(typeof(obj)) {
      case 'object': {
        var message = "";
        for (key in obj) {
          message += ", [" + key + "]: [" + obj[key] + "]";
        }
        if (message.length > 0) {
          message = message.substring(2); // chomp initial ', '
        }
        return message;
      }
      default: return "" + obj;
    }
  },

  debug: function(message) {
      if (this.shouldDebug) {
        alert("AjaxJS Message:\n\n" + message);
      }
  },

  error: function(message) {
      if (this.shouldDebug) {
        alert("AjaxJS ERROR:\n\n" + message);
      }
  },

  // trim() From Shawn Milo
  // https://lists.latech.edu/pipermail/javascript/2004-May/007567.html
  trim: function(str) {
    return str.replace(/^(\s+)?(.*\S)(\s+)?$/, '$2');
  },

  strip: function(str) {
    return str.replace(/\s+/, "");
  }

}

//function $() {
//Sutituyo el nombre de la siguiente función de $ a XX porque en las librerias JQuery, necesarias para PicasaWebIntegrator, ya existe
//una función llamada $ (y allí no consiguo sustituir el nombre)
function XX() {

    var elements = new Array();

    for (var i = 0; i < arguments.length; i++) {

      var element = arguments[i];

      if (typeof element == 'string') {
        if (document.getElementById) {
          element = document.getElementById(element);
        } else if (document.all) {
          element = document.all[element];
        }
      }

      elements.push(element);

    }

    if (arguments.length == 1 && elements.length > 0) {
      return elements[0];
    } else {
      return elements;
    }
}

function $C(elType) {
  return document.createElement(elType);
}

// From prototype library. Try.these(f1, f2, f3);
var Try = {
  these: function() {
    var returnValue;
    for (var i = 0; i<arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }
    return returnValue;
  }
}

function getElementsByClassName(classname) {
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = document.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

/* function getElementsByClassName(needle) {
  var xpathResult = document.evaluate('//*[@class = needle]', document, null, 0, null);
  var outArray = new Array();
  while ((outArray[outArray.length] = xpathResult.iterateNext())) {
  }
  return outArray;
}
*/

/*
  function acceptNode(node) {
    if (node.hasAttribute("class")) {
      var c = " " + node.className + " ";
       if (c.indexOf(" " + needle + " ") != -1)
         return NodeFilter.FILTER_ACCEPT;
    }
    return NodeFilter.FILTER_SKIP;
  }

  var treeWalker = document.createTreeWalker(document.documentElement,
                                             NodeFilter.SHOW_ELEMENT,
                                             acceptNode,
                                             true);
  var outArray = new Array();
  if (treeWalker) {
    var node = treeWalker.nextNode();
    while (node) {
      outArray.push(node);
      node = treeWalker.nextNode();
    }
  }
  return outArray;
}

*/

//Función de mi cosecha que se encarga de realizar el efecto necesario para que durante la espera a que devuelva algo la pagina 
//que se lanza en 2º la capa que se va a modificar indique dicha espera
function Mostrar_Estado_Cargando(prmtrIdCapa) 
	{
	var strSpanCargando = ""
	//shiftOpacity("result", 1000)
	opacity(prmtrIdCapa, 100, 25, 1000)
//	varCapa = XX(prmtrIdCapa);
//	strStyleSpanCargando = "background-color:#c0c0c0; color: #FFFFFF; font-weight: bold; width: 200px; "
//	strStyleSpanCargando += "text-align:left; padding:5px 10px; position:absolute;"
//	strSpanCargando = "<div style = '" + strStyleSpanCargando + "'>Cargando...</div>"
	//varCapa.innerHTML =  strSpanCargando + varCapa.innerHTML
	}
function Ocultar_Estado_Cargando(prmtrIdCapa)
	{opacity(prmtrIdCapa, 25, 100, 1500)}
	
function Mostrar_Estado_Cargando_RapidoOLD (prmtrIdCapa) 
	{XX(prmtrIdCapa).style.visibility = 'hidden'}
var objCapa 
function Ocultar_Estado_Cargando_RapidoOLD (prmtrIdCapa)
	{
	//XX(prmtrIdCapa).style.visibility = 'visible'
	objCapa = XX(prmtrIdCapa)
	window.setTimeout("objCapa.style.visibility = 'visible'", 800)
	}
	
var strColorCapaCargando
function Mostrar_Estado_Cargando_Rapido (prmtrIdCapa) 
	{
	strColorCapaCargando = XX(prmtrIdCapa).style.color
	XX(prmtrIdCapa).style.color = "silver"
	}

function Ocultar_Estado_Cargando_Rapido (prmtrIdCapa)
	{
	XX(prmtrIdCapa).style.color = strColorCapaCargando
	//window.setTimeout("objCapa.style.visibility = 'visible'", 800)
	}
	

function Obtener_Vbles_de_Formulario (prmtrNombreFormulario)
	{
	var objFormulario = document.forms[prmtrNombreFormulario]
//	Mostrar_Propiedades(objFormulario)
	var intI, intJ, strVbles, objReturn, vblesFormularioAux, strAux
	strVbles   = "vblesFormularioAux = "
	strVbles += "	{"
	for (intI= 0; intI < objFormulario.elements.length; ++intI)
		{
//		alert(objFormulario.elements[intI].name + "\ntype: " + objFormulario.elements[intI].type + "\nvalue: " + objFormulario.elements[intI].value)
//		alert("name: " + objFormulario.elements[intI].name + "\ntype: " + objFormulario.elements[intI].type + "\nvalue: " + objFormulario.elements[intI].value + "\nselectedIndex: " + objFormulario.elements[intI].selectedIndex)
		switch (objFormulario.elements[intI].type)
			{
			case "radio":
				strNombreRadio = objFormulario.elements[intI].name
				for (; intI < objFormulario.elements.length && strNombreRadio == objFormulario.elements[intI].name; ++intI)
					{
					//alert(intI + ": \nchecked" + objFormulario.elements[intI].checked + "\nselected" + objFormulario.elements[intI].selected)
					if (objFormulario.elements[intI].checked)
						{
						//strVbles += objFormulario.elements[intI].name + ": escape(\"" + objFormulario.elements[intI].value + "\"),"
						strVbles += objFormulario.elements[intI].name + ": \"" + escape(objFormulario.elements[intI].value) + "\","
						//strVbles += objFormulario.elements[intI].name + ": \"" + objFormulario.elements[intI].value + "\","
						}
					}
				--intI; // para que no se salte uno con el siguiente incremento de intI ¿puede que funcione mal cuando los radio button estén al final?
				break
//			case "select-one":
//				intIndice = formFichaCampeonato.cboCampeonatosMadre.selectedIndex
//				alert(intIndice + ": " + formFichaCampeonato.cboCampeonatosMadre [intIndice].text)
//				alert("select-one " + objFormulario.elements[intI].name + "\ntype: " + objFormulario.elements[intI].type + "\nvalue: " + objFormulario.elements[intI].value + "\nselectedIndex: " + objFormulario.elements[intI].selectedIndex)
//				alert(objFormulario.elements[intI])
//				strVbles += objFormulario.elements[intI].name + ": escape(\"" + objFormulario.elements[intI][objFormulario.elements[intI].selectedIndex].value + "\"),"
//				break
			default: 
				{
				if (objFormulario.elements[intI].type != "button")
					{strVbles += objFormulario.elements[intI].name + ": \"" + escape(objFormulario.elements[intI].value) + "\","}
				}
				//strVbles += objFormulario.elements[intI].name + ": \"" + objFormulario.elements[intI].value + "\","
			}
	
		}
	strVbles = strVbles.substr(0, (strVbles.length -1)) //elimino la última coma
	strVbles += "	}"
	//alert(strVbles) 
	objReturn = eval(strVbles)
//	Mostrar_Propiedades(objReturn)
	return objReturn
	}
	
	
//un poco... rebuscado pero erá la única forma de asignar el nombre de la capa a la función onResponse
function Cargar_Pagina (prmtrURLPagina, prmtrNombreCapa)
	{
	var strAux = ""
	strAux += "ajaxCaller.getPlainText('" + prmtrURLPagina + "', onResponse_Cargar_Pagina);"
	strAux += "function onResponse_Cargar_Pagina (prmtrText)"
	strAux += 	"{"
	strAux += 	"if (!Se_ha_producido_Error_en_AJAX (prmtrText))"
	strAux += 	"	{"
//	strAux += 	"		alert('prmtrText: ' + prmtrText);"
	strAux += 	"	XX('" + prmtrNombreCapa + "').innerHTML = prmtrText;}"
	strAux += 	"}"
//	alert(strAux)
	eval(strAux)
	}


//Ejecuto lo parentizado por <script language='javascript' type='text/javascript'></script>
//y cargo en la capa prmtrNombreCapa lo demas.
function OnResponse_Standart (prmtrText, prmtrNombreCapa)
	{
	var strAlert = ""
	strAlert += "prmtrNombreCapa:" + prmtrNombreCapa + "\n\n"

	var strEjecutarJScript, strInnerHTML, strNombreCapa
	strNombreCapa = (prmtrNombreCapa != null)?prmtrNombreCapa:'';
	strNombreCapa = (strNombreCapa == null && gblNombreCapa != null)?gblNombreCapa:prmtrNombreCapa;
	strAlert += "strNombreCapa:" + strNombreCapa + "\n\n"
	strAlert += "prmtrText:" + prmtrText
	//alert(strAlert)
//	var intPosInicioJScript = prmtrText.indexOf("//inicio ejecutar jscript")
//	var intPosFinJScript = prmtrText.indexOf("//fin ejecutar jscript") //"//fin ejecutar jscript".length()
//	if (intPosFinJScript > -1) {intPosFinJScript += 22} // para incluir tb el texto //fin ejecutar jscript
	var intPosInicioJScript = prmtrText.indexOf("<script language='javascript' type='text/javascript'>")
	var intPosFinJScript = prmtrText.indexOf("</script>") 
	if (!Se_ha_producido_Error_en_AJAX (prmtrText))
		{
		if (intPosFinJScript > -1) {intPosFinJScript += 9} // para incluir tb el texto </script>
		if (intPosInicioJScript > -1) 
			{strEjecutarJScript = prmtrText.substring(intPosInicioJScript, intPosFinJScript)
			//elimino el javascript para que me quede el resto aunque estuviera rodeando dicho jscript
			strInnerHTML = prmtrText.replace(strEjecutarJScript, "")
			//elimino los tag de script para que pueda hacer un eval del javascript
			strEjecutarJScript = strEjecutarJScript.replace("<script language='javascript' type='text/javascript'>", "")
			strEjecutarJScript = strEjecutarJScript.replace("</script>", "")
			}
		else
			{strEjecutarJScript = ""
			strInnerHTML = prmtrText}
		XX(strNombreCapa).innerHTML = strInnerHTML;
		//prompt(strEjecutarJScript, strEjecutarJScript)
		if (strEjecutarJScript != "") {eval(strEjecutarJScript)}
		}
	}
	
	
//ejecuto la parte de javascript que exista en el prmtrText y devuelvo el resto
function OnResponse_JavaScript (prmtrText)
	{
//	alert("dentro de OnResponse_JavaScript")
	var strEjecutarJScript, strInnerHTML 
//	var intPosInicioJScript = prmtrText.indexOf("//inicio ejecutar jscript")
//	var intPosFinJScript = prmtrText.indexOf("//fin ejecutar jscript") //"//fin ejecutar jscript".length()
//	if (intPosFinJScript > -1) {intPosFinJScript += 22} // para incluir tb el texto //fin ejecutar jscript
	var intPosInicioJScript = prmtrText.indexOf("<script language='javascript' type='text/javascript'>")
	var intPosFinJScript = prmtrText.indexOf("</script>") 
	if (!Se_ha_producido_Error_en_AJAX (prmtrText))
		{
		if (intPosFinJScript > -1) {intPosFinJScript += 9} // para incluir tb el texto </script>
		if (intPosInicioJScript > -1) 
			{strEjecutarJScript = prmtrText.substring(intPosInicioJScript, intPosFinJScript)
			//elimino el javascript para que me quede el resto aunque estuviera rodeando dicho jscript
			strInnerHTML = prmtrText.replace(strEjecutarJScript, "")
			//elimino los tag de script para que pueda hacer un eval del javascript
			strEjecutarJScript = strEjecutarJScript.replace("<script language='javascript' type='text/javascript'>", "")
			strEjecutarJScript = strEjecutarJScript.replace("</script>", "")
			}
		else
			{strEjecutarJScript = ""
			strInnerHTML = prmtrText}
		//alert(strEjecutarJScript)
		if (strEjecutarJScript != "") {eval(strEjecutarJScript)}
		}
	return strInnerHTML
	}
	
//la siguiente funcion observa si en el texto devuelto por AJAX existe un "subtexto" que nos chive
//la existencia de un casque en el código, redirigiendo a la gestión adecuada del error si es así.
function Se_ha_producido_Error_en_AJAX (prmtrTextoOnResponse)
	{
	var blnSeHaProducidoError = -1
	var prmtrTextoIdentificadorError = "Se ha producido un <strong>error</strong> en la página"
	//alert(prmtrTextoOnResponse.indexOf(prmtrTextoIdentificadorError))
	//alert(prmtrTextoOnResponse)
	blnSeHaProducidoError = prmtrTextoOnResponse.indexOf(prmtrTextoIdentificadorError)
	//alert(blnSeHaProducidoError)
	//Si se ha producido un error, es decir blnSeHaProducidoError > -1, muestro la pantalla de error
	//indicandole que el error viene desde AJAX (desdeAJAX=true) y tome las medidas adecuadas comentadas en dicha página.
	if (blnSeHaProducidoError > -1) 
		{document.location.href = "../_Librerias/Error.asp?desdeAJAX=true"}
	blnSeHaProducidoError = (blnSeHaProducidoError == -1)?false:true;
	//alert(blnSeHaProducidoError)
	return blnSeHaProducidoError
	}

//Cargo una página en el elemento tooltip
//la siguiente vble indica que codigo ejecutar al hacer onResponse.
var strEvalOnResponse
function Cargar_pagina_en_Tooltip_AJAX (prmtrPaginaACargar, prmtrEsEstatica, prmtrEvalOnResponse)
	{
	ddrivetip("cargando...", prmtrEsEstatica, 400)
	strEvalOnResponse = prmtrEvalOnResponse
	ajaxCaller.getPlainText(prmtrPaginaACargar, onResponse_Cargar_pagina_en_Tooltip_AJAX);
	}
function onResponse_Cargar_pagina_en_Tooltip_AJAX (prmtrText)
	{

	if (!Se_ha_producido_Error_en_AJAX (prmtrText))
		{tipobj.innerHTML = prmtrText}
	//alert(strEvalOnResponse)
	if (strEvalOnResponse != null)
		{//alert(strEvalOnResponse)
		eval(strEvalOnResponse)}
	}	
	
	
	
	
/*var capaCargarPagina
function Cargar_Pagina (prmtrURLPagina, prmtrNombreCapa)
	{
	capaCargarPagina = prmtrNombreCapa 
	ajaxCaller.getPlainText(prmtrURLPagina, onResponse_Cargar_Pagina);
	}
function onResponse_Cargar_Pagina (prmtrText)
	{
	var varCapa = XX(capaCargarPagina);
//		alert("prmtrText: " + prmtrText)
	varCapa.innerHTML = prmtrText;
	}
	*/
	
	
//Mejoras introducidas en cada una de las versiones
//-v1:
//	    - Agrego las funciones 
//				· Cargar_Pagina
//				· Mostrar_Estado_Cargando, 
//				· Ocultar_Estado_Cargando, 
//				· Obtener_Vbles_de_Formulario
//
