// PHPFrameWork
// Libreria de auxiliares
// ====================================================

// Cambia la visibilidad de un elemento via estilo CSS
function toggleVisibility(e){

	if (Element.visible(e)){
		Element.hide(e);
	}
	else {
		Element.show(e);
	}
}

// hace swap de visibilidad entre 2 elementos
// @param desaparece elemento a desaparecer
// @param aparece elemento a apareer
function swapVisible(desaparece, aparece) {

	Element.hide(desaparece);
	Element.show(aparece);
}



var estadoVentanas = new Array();
// Muestra o esconde una ventanaDiv indicando el tipo de efecto a utilizar
// en la posicion del mouse, desplazado x horizontalmente e y verticalmente
// @param id ventana
// @param tipo de transicion
// @param x desplazamiento horizontal desde la posicion X del mouse
// @param y desplazamiento vertical desde la posicion Y del mouse
function toggleVentanaDivOnMouse(id, tipo, x, y) {
	
	var o = $(id);
	

	if(estadoVentanas[id] == true) {

		Effect.toggle(id, tipo, {duration: 0.3});
		estadoVentanas[id] = null;
		return true;
	}

	o.style.left = mouseX - parseInt(o.style.width);
	o.style.top = mouseY + 15;
	Effect.toggle(id, tipo);
	estadoVentanas[id] = true;

	//alert("x = " + mouseX + " y = " + mouseY + " width = " + o.style.width);
}



// SCRIPT DE CAPTURA DE POSICION DE MOUSE
// ======================================
var IE = document.all?true:false

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE)

var mouseX;
var mouseY;

function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    mouseX = event.clientX + document.body.scrollLeft
    mouseY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    mouseX = e.pageX
    mouseY = e.pageY
  }  
  // catch possible negative values in NS4
  if (mouseX < 0){tempX = 0}
  if (mouseY < 0){tempY = 0}  

  return true

}
document.onmousemove = getMouseXY;



function reloadImagenVerificadora(id) {

	if(typeof(id) == "string")
		var img = $(id);
	else
		var img = id;
		
	if(typeof(img) == "undefined")
		return;
	
	var random = Math.round(Math.random()*1000) + "";
	
	var url = img.src;
	
	if(url.indexOf("&dummy=") < 0)
		url += "&dummy=" + random;
	else {
	
		url = url.substring(0, url.indexOf("&dummy="));
		url += "&dummy=" + random;
	}
	
	img.src = url;
	
}


// Rellena el contenido de un combobox en base a un arreglo, dependiendo de la posicion
// seleccionada en otro combobox
// =====================================================================================
function fillSelectFromArray(selectCtrl, itemArray, goodPrompt, badPrompt, defaultItem) {

	var i, j;
	var prompt;

	// empty existing items
	for (i = selectCtrl.options.length; i >= 0; i--) {
		selectCtrl.options[i] = null; 
	}

	prompt = (itemArray != null) ? goodPrompt : badPrompt;
	
	if (prompt == null) {
		j = 0;
	}
	else {
		selectCtrl.options[0] = new Option(prompt);
		j = 1;
	}

	if (itemArray != null) {
		// add new items
		for (i = 0; i < itemArray.length; i++) {
			selectCtrl.options[j] = new Option(itemArray[i][0]);

			if (itemArray[i][1] != null) {
				selectCtrl.options[j].value = itemArray[i][1]; 
			}
			j++;
		}
		// select first item (prompt) for sub list
		selectCtrl.options[0].selected = true;
	}
}

function xmlValue(xml, tagName, index) {

//	alert(xml)

	if(xml.getElementsByTagName(tagName).length == 0)
		return null;

	return xml.getElementsByTagName(tagName)[index].childNodes[0].nodeValue;	
}

function getSelectIndexOf(select, value) {


	try {
		
		for(var i = 0; i < select.options.length; i++) {
			
			if(select.options[i].value == value)
				return i;
		}
	}
	catch(e) { return -1 }
	
}

// Agrega los puntos separadores de miles, ASUME ENTRADA ENTERA
// EJ: 232234 -> 232.234
function clNumber(numero) {
	
	if(numero == null || typeof(numero) == "undefined")
		return null;	
		
	if((numero+"").indexOf(".") >= 0)
		return numero;
	
	var aux = numero + "";
	var retorno = "";	
		
	while(aux.length > 3) {

		var trozo = aux.substr(aux.length-3, 3);
		aux = aux.substring(0, aux.length-3);
		
		retorno = "." + trozo + retorno;
	}
	
	retorno = aux + retorno;
	
	return retorno;
	
}

function unClNumber(numero) {

	if(numero == null || typeof(numero) == "undefined")
		return;
		
	var aux = "" + numero;
	
	for(var i = 0; i < aux.length; i++) {

		if(aux.charAt(i) == '.') {
			aux = aux.substr(0, i) + aux.substring(i+1, aux.length);
		}
	}

	if(isNaN(aux))
		return numero;

	
	return parseInt(aux);
}

function tacharFila(element) {
	
	if(typeof(element) == "undefined" || element == null)
		return;

	var tr = getParentTR(element)

	var hijos = tr.childNodes;
	
	for(var i = 0; i < hijos.length; i++) {
	
		if(hijos[i].tagName == "TD")
			Element.addClassName(hijos[i], 'tachado');
	}
}

function getParentTR(element) {

	for(var aux = element; aux != null; aux = aux.parentNode) {
		
		if(aux.tagName == "TR")
			return Element.extend(aux);
	}	
}


function getParentTBody(element) {

	for(var aux = element; aux != null; aux = aux.parentNode) {
		
		if(aux.tagName == "TBODY" || aux.tagName == "TABLE")
			return Element.extend(aux);
	}		
	
}

function getParentTable(element) {

	for(var aux = element; aux != null; aux = aux.parentNode) {
		
		if(aux.tagName == "TABLE")
			return Element.extend(aux);
	}		
		
}

function getLoading(elemento) {
	
	var aux = Element.extend(elemento);
	var loading = aux.getElementsByClassName('dummyLoading')
		
	if(loading.length > 0)
		return loading[0]
	
	
	aux = Element.extend(elemento.parentNode);
	loading = aux.getElementsByClassName('dummyLoading')
		
	if(loading.length > 0)
		return loading[0]
		
	return null;
}

function nl2br(s) {

		return s.replace(/\n/g, "<br>");
}


function clNumberCampo(campo) {
	
	if(isNaN(campo.value) || campo.value == "")
		return;
		
	campo.value = clNumber(campo.value);
	
}

function unClNumberCampo(campo) {
	
	if(campo.value == "")
		return;

	campo.value = unClNumber(campo.value);		
}

function roundNumber(rnum, rlength) {

	if (rnum > 8191 && rnum < 10485) {
		rnum = rnum-5000;
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
		newnumber = newnumber+5000;
	} else {
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	}
	return newnumber;
}

function xmlValue(xml, tagName, index) {

	try {
		if(xml.getElementsByTagName(tagName).length == 0)
			return null;
	
		var nodos = xml.getElementsByTagName(tagName)[index].childNodes;
		var valor = "";
	
		for(var i = 0; i < nodos.length; i++)
			valor += nodos[i].nodeValue;

		valor = valor.replace(/&amp;/g, "&");
		return valor;
	}
	catch(e) { return null; }
}

/**
 * 
 */		
function showVirtualPopup(html, pxtop, pxleft, pxwidth, pxheight) {


	var d = new Date();
	var ID = "virtualPopup" + d.getTime()

	var contenido = Builder.node("div", {id: ID, virtualPopup: true, className: "virtualPopupContenido"})
	Element.extend(contenido);
	contenido.innerHTML = html
		
	
	if(typeof(pxwidth) != "undefined") 		
		contenido.style.width = pxwidth;
		
	if(typeof(pxheight) != "undefined")
		contenido.style.height = pxheight;
		
	contenido.style.top = pxtop;
	contenido.style.left = pxleft;
	contenido.style.display = "none";

	document.body.appendChild(contenido);	
	var dimensionesContenido = contenido.getDimensions();

	var cierre = Builder.node("img", {src: "img/close01.gif", className: "virtualPopupContenidoCierre"})
	cierre.style.top = 2
	cierre.style.left = dimensionesContenido.width - 16 - 4;
	Event.observe(cierre, "click", function(event) { closeVirtualPopup(Event.element(event)) } )
	Event.observe(cierre, "mouseover", function(event) { Element.toggleClassName(Event.element(event), 'virtualPopupContenidoCierreHover') })
	Event.observe(cierre, "mouseout", function(event) { Element.toggleClassName(Event.element(event), 'virtualPopupContenidoCierreHover') })
	contenido.appendChild(cierre);
	
	var sombra1 = Builder.node("div", {id: ID + "sombra1", className: "virtualPopupSombra1"})
	sombra1.style.width = dimensionesContenido.width
	sombra1.style.height = dimensionesContenido.height
	sombra1.style.top = pxtop + 3;
	sombra1.style.left = pxleft + 3;	
	sombra1.style.display = "none";
	
	var sombra2 = Builder.node("div", {id: ID + "sombra2", className: "virtualPopupSombra2"})
	sombra2.style.width = dimensionesContenido.width
	sombra2.style.height = dimensionesContenido.height
	sombra2.style.top = pxtop + 4;
	sombra2.style.left = pxleft + 4;		
	sombra2.style.display = "none";
	
	document.body.appendChild(sombra1);
	document.body.appendChild(sombra2);
	
	Effect.Appear(contenido, {duration: 0.3, afterFinish: function() {
		
		
		Effect.Appear(sombra1, {duration: 0.1, to: 0.25});
		Effect.Appear(sombra2, {duration: 0.1, to: 0.25})
	} })
	
	return cierre;

}

function closeVirtualPopup(element) {
	
	var popup = null;
	
	try {

		if(typeof(element) == "string") {
		
			popup = $(element)	
		}
		else  {
		
			if(element.readAttribute("virtualPopup") == "true") {
				
				popup = element;			
			}
			else {
				
				popup = element.up('[virtualPopup="true"]');	
			}
		}
	}
	catch(e) {
	
		popup = element.up('[virtualPopup="true"]')	
	}

	var id = popup.id
	var sombra1 = $(id + "sombra1")
	var sombra2 = $(id + "sombra2")

	Effect.Fade(sombra1, {duration: 0.2, afterFinish: function() { delete(sombra1) } })		
	Effect.Fade(sombra2, {duration: 0.2, afterFinish: function() { delete(sombra2) } })	
	Effect.Fade(popup, {duration: 0.4, afterFinish: function() { delete(popup); } })
	
	
	
	
}

window.checkTeclaNumerica = function(event) {
	
	try {
		
		if(event.keyCode == Event.KEY_BACKSPACE)	
			return true
	}
	catch(e) { }

	var teclasPermitidas = [46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8]
	
	if(typeof(event.charCode) == "undefined") {

		var codigo = event.keyCode		
	}
	else {

		var codigo = event.charCode;
	}
	
	if(teclasPermitidas.indexOf(codigo) == -1)
		return false;
		
	return true;
}

function mouseOver(elemento) {
	
	if(typeof(arguments[1]) != "undefined") {
	
		Element.addClassName(elemento, arguments[1])
	}
	else {

		Element.addClassName(elemento, 'mouseOver')
		Element.addClassName(elemento, 'clickeable')
		
	}
	
}

function mouseOut(elemento) {

	if(typeof(arguments[1]) != "undefined") {
	
		Element.removeClassName(elemento, arguments[1])
	}
	else {
	
		Element.removeClassName(elemento, 'mouseOver')
		Element.removeClassName(elemento, 'clickeable')
	}	
}


function getLink(link, callback) {

	if(!callback)
		return;

	new Ajax.Request(urlConsultaXML, {parameters: "consulta=getlink&link=" + link, onComplete: function(transport) { getLinkCallback(transport, callback) } });
	
}

function getLinkCallback(transport, callback) {
	
	var xml = transport.responseXML
	
	callback(xmlValue(xml, "link", 0));
}

function llenarSelect(select, arreglo) {
	
	if(typeof(select) != "object" || (typeof(arreglo) != "array" && typeof(arreglo) != "object")) {
	
		try  { 
			
			select.options.length = 0;
			select.options[0] = new Option("-- Sin datos --", -1);	
		}
		catch(e) { }
		
		return;
	}
				
	select.options.length = 0;
	
	if(arreglo.length > 0) { 
			
		for(var i = 0; i < arreglo.length; i++) {
			
			select.options[i] = new Option(arreglo[i].text, arreglo[i].value);
		}			
	}
	else {

		select.options[0] = new Option("-- Sin datos --", -1);			
	}
}

function completarString(str, chr, largo, derecha) {
	
	var aux = str + "";
	
	if(aux.length >= largo)
		return aux;
		
	var relleno = ("" + chr).times(largo - aux.length);
	
	if(derecha)
		return str + relleno
	else
		return relleno + str;	
}

function fechaLatina(fechaString) {

	var separador = "";

	if(fechaString.indexOf("/") > 0) {
	
		separador = "/";
	}
	else {
	
		if(fechaString.indexOf("-") > 0)
			separador = "-";	
		else 
			return fechaString
	}
	
	fechaString = fechaString.strip();
	
	// timestamp o fecha?
	if(fechaString.indexOf(" ") > 0) {
		
		var partes = fechaString.split(" ")
		
		if(partes.length != 2)
			return fechaString
			
		var partesFecha = fechaString.split(separador)
		
		if(partesFecha.length != 3)
			return fechaString
			
		return partesFecha[2] + "/" + partesFecha[1] + "/" + partesFecha[0] + " " + partes.substr(0, 5);
	}
	else {
		
		var partesFecha = fechaString.split(separador)
		
		if(partesFecha.length != 3)
			return fechaString
			
		return partesFecha[2] + "/" + partesFecha[1] + "/" + partesFecha[0] ;
		
	}
	
}


function pngIEFix() {

	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	
	if ((version >= 5.5) && (document.body.filters)) 
	{
	   for(var i=0; i<document.images.length; i++)
	   {
	      var img = document.images[i]
	      var imgName = img.src.toUpperCase()
	      if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	      {
	         var imgID = (img.id) ? "id='" + img.id + "' " : ""
	         var imgClass = (img.className) ? "class='" + img.className + "' " : ""
	         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
	         var imgStyle = "display:inline-block;" + img.style.cssText 
	         if (img.align == "left") imgStyle = "float:left;" + imgStyle
	         if (img.align == "right") imgStyle = "float:right;" + imgStyle
	         if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
	         var strNewHTML = "<span " + imgID + imgClass + imgTitle
	         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
	         img.outerHTML = strNewHTML
	         i = i-1
	      }
	   }
	}
}


// PROTOTYPE EXTENSIONS
// ================================================================================
var PHPFWPrototypeExtensions = {
	
	centrar: function(element, elementoDest) {

		var dest = $(elementoDest)
		
		var destPos = dest.positionedOffset();
		var destSize = dest.getDimensions();
		
		var elementSize = $(element).getDimensions();
		
		var x = parseInt(destPos[0] + (destSize.width - elementSize.width)/2)
		var y = parseInt(destPos[1] + (destSize.height - elementSize.height)/2)
		
		$(element).style.left = x
		$(element).style.top = y
	},

	isParent: function(element, child) {

		for(var aux = $(child); aux != null; aux = aux.parentNode) {
				
			if(aux.parentNode == element)
				return true;
		}
		
		return false;
	}
}

Element.addMethods(PHPFWPrototypeExtensions)

