
function $(id)
{
	return document.getElementById(id);
}
function text(id, tx)
{
	var d = $(id);
	if(d){
		d.innerHTML = tx;
	}
}

function TRACE(tx)
{
	var d = $("debug");
	if(d){
		d.innerHTML += tx;
	}
}
function TRACELN(tx)
{
	TRACE(tx + "<br>\r\n");
}

function show(id, f)
{
	//document.getElementById(id).style.display = f ? "block" : "none";
	document.getElementById(id).style.display = f ? "" : "none";
}
function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}
function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\s)'+searchClass+'(\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

///////////////////////////////////////////////////////////////
//Añade métodos a Date
Date.prototype.soloFecha=function()
{
	var tx = this.toLocaleString();
	var i  = tx.indexOf(",");
	var j  = tx.indexOf(this.getFullYear());
	return tx.substring(i+1, j+4);
}

Date.prototype.formatDate=function(){
	var v = this.toLocaleString();
	var n = v.length;
	if(v[n-8] == " ") n++;
	return v.substring(0, n-9);
}
Date.prototype.formatTime=function(){
	var v = this.toLocaleString();
	var n = v.length;
	if(v[n-7] == " ") n++;
	return v.substring(n-8);
}

Date.prototype.roundMilisec=function(v)
{
	t = this.getTime();
	t = Math.floor(t / v);
	this.setTime(t * v);
}

Date.prototype.roundSec=function(v)
{
	this.roundMilisec(1000*v);
}
Date.prototype.roundMin=function(v)
{
	this.roundMilisec(60*1000*v);
}
Date.prototype.roundHour=function(v)
{
	this.roundMilisec(60*60*1000*v);
}
//---
Date.prototype.addMilisec=function(v)
{
	t = this.getTime();
	t += v;
	this.setTime(t);
}
Date.prototype.addSec=function(v)
{
	this.addMilisec(1000*v);
}
Date.prototype.addMin=function(v)
{
	this.addMilisec(60*1000*v);
}
Date.prototype.addHour=function(v)
{
	this.addMilisec(3600*1000*v);
}
Date.prototype.addDay=function(v)
{
	this.addMilisec(24*3600*1000*v);
}
//--------
function DosDigitos(v)
{
	return v < 10 ? "0" + v : "" + v;
}
//Date.estática, convierte 'segundos' en string
Date.formatCompact=function(sec)
{
	var tx="";
	var t = new Date(sec * 1000);
	
	tx += DosDigitos(t.getDate());
	tx += "/" + DosDigitos(1+t.getMonth()) + "/";
	tx += t.getFullYear();
	
	tx += " " + DosDigitos(t.getHours());
	tx += ":" + DosDigitos(t.getMinutes()) + ":";
	tx += DosDigitos(t.getSeconds());
	
	return tx;
}
//Date.estatica, desde string obtiene 'segundos'
Date.fromCompact=function(tx)
{
	var a = tx.split(" ");
	var d = a[0].split("/");
	var t = a[1].split(":");
	var r = new Date(0);
	r.setFullYear(d[2]);
	r.setMonth(d[1]-1);
	r.setDate(d[0]);
	r.setHours(t[0]);
	r.setMinutes(t[1]);
	r.setSeconds(t[2]);
	return r.getTime() / 1000;
}
//////////////////////////////////////////////////////////////////
/*string.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g, '') ;
}*/
function trim(str)
{
	return str.replace(/^\s+|\s+$/g, '') ;
}

//////////////////////////////////////////////////////////////////


function sprintf()
{
	var i;
	var ia = 1;
	var ar = arguments[0].split("%");
	var txt = ar[0];
	for(i = 1; i< ar.length;i++){
		switch(ar[i].charAt(0)){
			case "s":
				txt += arguments[ia++] + ar[i].substring(1);
				break;
			case "S":
				txt += "\"" + arguments[ia++] + "\"" + ar[i].substring(1);
				break;
			default:
				txt += ar[i];
				break; 
		}
	}
	return txt;
}
function parseSearch()
{
	var ret = new Array();
	var tx = location.search;
	var param;
	if(tx == null || tx.length < 1) return ret;
	tx = tx.substring(1); // quita el signo ?
	tx = tx.split("&");
	for(i in tx){
		param = tx[i].split("=");
		if(param.length == 2){
			ret[param[0]] = param[1];
		}
	}
	return ret;
}
function makeUrl (url, params)
{
	var kei, s;
	s = "?";
	for(kei in params){
		url += s + kei + "=" + params[kei]
		s = "&";
	}
	return url;
}
function linkFalse(tx, js)
{
	return "<a href=\"#\" onclick=\"" + js + "return false\">" + tx + "</a>"; 
}
function setCookie(nombre, valor, caducidad)
{
  document.cookie = nombre + "=" + escape(valor) 
  + ((caducidad == null) ? "" : ("; expires=" +  caducidad.toGMTString())); 
} 

function getCookie(nombre)
{
	var buscamos = nombre + "="; 
	if (document.cookie.length > 0) {
		i = document.cookie.indexOf(buscamos); 
	    if (i != -1) 	{ 
			i += buscamos.length; 
			j = document.cookie.indexOf(";", i); 
      		if (j == -1) return unescape(document.cookie.substring(i));
      		else         return unescape(document.cookie.substring(i,j));
	    }
    } 
  return "";
}
 
function deleteCookie( nombre ) {
	document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

//----------------------------
//HTML
function HTML()
{
}

HTML.propiedades = function (props)
{
	var i, salida;
	salida = "";
	for(i in props){
		salida += " " + i + "=\"" + props[i] + "\"";
	}
	return salida;
}

HTML.table = function (txt, props)
{
	if(!props) props = new Array();
	return "<table" + HTML.propiedades(props) + ">" + txt + "</table>";
}
HTML.tr = function (txt, props)
{
	if(!props) props = new Array();
	return "<tr" + HTML.propiedades(props) + ">" + txt + "</tr>";
}
HTML.td=function (txt, props)
{
	if(!props) props = new Array();
	return "<td" + HTML.propiedades(props) + ">" + txt + "</td>";
}
//////////////////////////////////////////////////////////////////////////////
// AJAX --
var myx_req=null;
var myx_event;
function myx_callback()
{
	var texto;
	var std;
	if(myx_req == null || myx_req.readyState != 4) {
  		return;
  	}
  	texto = myx_req.responseText;
  	std   = myx_req.status;
 	myx_req = null;
	if(std == 200) {
		myx_event(texto); 	
  	}
}
//crea el objeto ajax, le asigna callback
function myx_create(callback) 
{
	if(myx_req != null){
		myx_req.abort();
		myx_req  = null;
	}	
	myx_event = callback;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			myx_req = new XMLHttpRequest();
        } catch(e) {
			myx_req = null;
        }
    }
    // branch for IE/Windows ActiveX version
	else if(window.ActiveXObject) {
       	try {
        	myx_req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		myx_req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		myx_req = null;
        	}
		}
    }
    if(myx_req){
		myx_req.onreadystatechange = myx_callback;
    }
    return myx_req != null;
}

function myx_leer(url, callback) 
{
	if(myx_create(callback)){
		myx_req.open("GET", url, true);
		myx_req.send("");
	}
}
function myx_poner(url, callback, datos) 
{
	if(myx_create(callback)){
		myx_req.open("POST", url, true);
		myx_req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
 		myx_req.send(datos);
	}
}
function myx_cancelar()
{
	if(myx_req != null){
		myx_req.abort();
		myx_req  = null;
	}	
}
//-----------------------------------------------------------------
/*////////////////////////////////////////////////////////////////////////////
Ejemplo: Var req = new ActiveXObject("MicrosoftXMLHTTP"); 

METODOS del XmlHttpRequest

abort() 								Stops the current request 
setRequestHeader("label", "value") 		Assigns a label/value pair to the header to be sent with a request 
send(content) 							Transmits the request, optionally with postable string or DOM object data 
open("method", "URL"[, asyncFlag[,"userName"[, "password"]]]) 	Assigns destination URL, method, and other optional attributes of a pending request 
getResponseHeader("headerLabel") 		Returns the string value of a single header label 
getAllResponseHeaders() 				Returns complete set of headers (labels and values) as a string 
abort() 								The XmlHttpRequest Object Methods Stops the current request 

PROPIEDADES del XmlHttpRequest

onreadystatechange 			Event handler for an event that fires at every state change 
readystate 
	0 = uninitialized 
	1 = loading 
	2 = loaded 
	3 = interactive 
	4 = complete 
 
responseText 	String version of data returned from server process 
responseXml 	DOM-compatible document object of data returned from server process 
status 			Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK" 
statusText 		String message accompanying the status code 

////////////////////////////////////////////////////////////////////////////*/
var respuesta = Array();
function Ajax(php)
{
	this.request = null;
	this.php     = php ? php : "index.php";
}
Ajax.prototype.CreateRequest = function()
{	
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			this.request = new XMLHttpRequest();
        	//for(i in this.request){        		alert(i);        	}
        } catch(e) {
			this.request = null;
        }
    }
    // branch for IE/Windows ActiveX version
	else if(window.ActiveXObject) {
       	try {
        	this.request = new ActiveXObject("Msxml2.XMLHTTP");
        	//for(i in this.request){        		alert(i);        	}
      	} catch(e) {
        	try {
          		this.request = new ActiveXObject("Microsoft.XMLHTTP");
        		//for(i in this.request){        		alert(i);        	}
        	} catch(e) {
          		this.request = null;
        	}
		}
    }
    if(this.request){
    	var that = this;
		this.request.onreadystatechange = function() { that.callback()};
    }
}

Ajax.prototype.callback= function()
{
	if(this.request == null) {
		//alert("norequest");
  		return;
  	}
	if(this.request.readyState != 4) {
		//alert(this.request.readyState);
  		return;
  	}
	if(this.request.status == 200) {
		if(this.onCallbackOk) this.onCallbackOk(this.request.responseText); 	
  	}
  	else{
		if(this.onCallbackKo) this.onCallbackKo(); 	
  	}
} 
Ajax.prototype.isRunning= function()
{
	return this.request != null && this.request.readyState != 4;
}
Ajax.prototype.get=function(url)
{
	this.CreateRequest();	
	this.request.open("GET", url, true);
	this.request.send("");
}
Ajax.prototype.getphp=function(params)
{
	var url = makeUrl(this.php, params);
//	alert(url);
	this.get(url);
}

Ajax.prototype.cancelar=function()
{
	if(this.request != null){
		this.request.abort();
		this.request  = null;
	}	
}
Ajax.parseRespuesta=function(v)
{
  var i, e;
  //alert(v);
  //texto de error para mostrar
  if(v.indexOf("respuesta") != 0){
    return false;
  } //O json para parsear
 // alert(v);
  eval(v); //esto carga el array respuesta
  for(i in respuesta){
    //alert(i + " => " + respuesta[i]);
    e = $(i);
    if(e){
      	e.innerHTML = respuesta[i]; //contiene texto para un div
    }
    else{
		eval(respuesta[i]); //o es un script para evaluar
    }
  }
  return true;
}
//---------------------------------------
//evento generado por boton BACK
function onBackHistory()
{
  if(Page.actual != null){
    setTimeout("Page.actual.onBackHistory();", 100);
  }
}
//<div id="fristo"><iframe src="/lib/history1.html" name="DUMY" height="0" width="0"> </iframe></div>
//-----------------------------------------------------------------
function Page(n, a)
{
	this.name      = n;
	this.anterior  = a;
	this.innerHTML = null;
	this.page_div = "pral_div";
}

Page.actual = null;

Page.unsetActual=function()
{
	if(Page.actual && Page.actual.onUnsetActual) Page.actual.onUnsetActual();
	Page.actual = null;
}
Page.prototype.setActual=function()
{
	var txt="";
	var js, v, n;
	Page.unsetActual();
	Page.actual = this;
	if(this.innerHTML) { text(this.page_div, this.innerHTML); }
	if($("path_div")){
		txt = this.name;
		n   = 1;
		for(v = this.anterior; v ;v = v.anterior){
			js  = sprintf("Page.onBackCount(%s);", n++);
			txt = linkFalse(v.name, js) + " &gt; " + txt; 
		}
		text("path_div",txt);
	}
	if(this.onSetActual) this.onSetActual(); 
}
Page.prototype.onBackHistory=function()
{
	if(this.anterior == null) return;
	this.anterior.activar();
}
Page.onBackCount=function(n)
{
	v = Page.actual;
	while(n--) v = v.anterior;
	v.activar();
}
Page.prototype.activar=function()
{
	alert(name + " debe sobrecargar activar();");
	this.setActual();
}
Page.prototype.onCallbackActivar = function(tx, a)
{
	if(a)  this.anterior  = a;
	if(tx) this.innerHTML = tx;
	this.setActual();
}
//-----------------------------------------------------------------

