function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
	//Netscape compliant
	scrOfY = window.pageYOffset;
	scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	//DOM compliant
	scrOfY = document.body.scrollTop;
	scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	//IE6 standards compliant mode
	scrOfY = document.documentElement.scrollTop;
	scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

if ( '\v' == 'v' ){ // SOLO EN IE DEVUELVE TRUE
	// Se extiende el metodo substr para que acepte numeros negativos
	var substr = String.prototype.substr;
	String.prototype.substr = function(s) {
		if (s < 0) s = this.length + s;
		return substr.apply(this, arguments);
	}
}

function updateCalendario( f ){
	var ajax = new uniAjax();
	var calendario = ajax.leer( '/_buscadorCalendario.asp?diaCalendario=' + f );
	xId( 'contenedor_calendario' ).innerHTML = calendario;
	var tooltip = new TOOLTIP('calendarToolTip','a.chicaAviso', '/ajaxToolTip.asp',{
		showTime: 1.5,
		ajaxOptions: { asynchronous: false }
	});
}

function xId( id ){
	return document.getElementById( id );
}

function myIsDate(mystring)	{ var mystring, myresult ;
	isNaN(mystring)? myresult=false : myresult=true ;
	var mystring = new Date(mystring);
	isNaN(mystring)? myresult=false : myresult=true ;
	return myresult ; 
}	
	
function validarTodo(){ ret = true;
	if (!myIsDate( $F('fecha') ) ) ret = false;
	if ( $F('titulo') == '' ) ret = false;
	if ( $F('descripcion') == '' ) ret = false;
	return ret ;
}
	
function mostrarRes(r){ 
	var respuesta = r.responseText;
	if ( respuesta.indexOf("xxNOHAYSESSIONxx") > -1 ){
		alert('Sr. Usuario: \r\nPor inactividad se ha deslogueado automticamente. \r\nSer redirijido a la pgina');
		window.location.href = './default.asp'
	}else{
		$('nuevaFecha').update( r.responseText );
		actualizarPanel();
		setTimeout("$('nuevaFecha').fade({duration:0.5})",2000);
	}
}

function abrirAcordeon(e){ 
	var menu = Event.element(e); // El elemento attachado al evento
	if ( menu.tagName == 'IMG' ) { // si hizo click en la imagen al abrir el acordeon
		var img = menu ; // el elemento que esta en la variable menu es la imagen y la guardo en una variable
		menu = menu.up(); // y el menu esta arriba
	}else var img = menu.down(); // si hizo click en el menu, la guardo en una variable
	
	img.src = '/images/loader.gif';
	var menu_inner = 'mis_' + menu.id.substr(7,menu.id.length);
	
	if ( $(menu_inner).visible() ){
		Effect.BlindUp(menu_inner,{
			duration:1,
			queue:{ position: 'end', scope: 'scope_acordeon' },
			beforeStart: function(){ img.src = '/images/add.gif'; }			
		});
		return false;
	}

	Effect.BlindDown( menu_inner,{ 
		duration:1, 
		afterFinish: function(){ 
			img.src = '/images/menos.gif'; 
		} 
	});

	$$('.acordeon').each( function(el){ 
		if ( el.id != menu_inner ){
			Effect.BlindUp(el, {
				duration:1,
				beforeStart: function(){ 
					var ximg = $('titulo_' + el.id.substr(4,el.id.length)).down()
					ximg.src = '/images/add.gif'; 
				}
			}); 
		}
	});		
 }
function actualizarCaja(i)	{ 
	if ( typeof i == 'undefined' ) { i = ''; }
	var caja = $('pasaje');
	new Ajax.Updater(caja, 'miColegioPIO.asp?panel=nuevaFecha',{
		parameters:{ 'key' : i } ,
		onComplete: function(r){
			var respuesta = r.responseText;
			if ( respuesta.indexOf("xxNOHAYSESSIONxx") > -1 ){
				alert('Sr. Usuario: \r\nPor inactividad se ha deslogueado automticamente. \r\nSer redirijido a la pgina');
				window.location.href = './default.asp';
			}else centrarCaja(caja);
		}
	});
}
function centrarCaja(caja)	{ 	
//	var dWH = document.viewport.getDimensions(); // me devuelve la dimension de la pantalla ( width y height )
//	var sWH = document.viewport.getScrollOffsets(); // me devuelve la posicion del scroll ( left y top ) 
//	var cWH = caja.getDimensions(); // me devuelve la dimension de la caja ( width y height )
//	var xCaja = (dWH.width + sWH.left) / 2 - cWH.width / 2
//	var yCaja = (dWH.height + sWH.top) / 2 - cWH.height / 2
//	caja.setStyle({left:xCaja+'px',top:yCaja+'px'}).appear({duration:0.5});
	document.getElementById('tapa').style.display = '';
	document.getElementById('divPop').style.display = '';
 }
 
function actualizarPanel(){
	new Ajax.Updater('panel', 'miColegioPIO.asp?panel=panelTodo',{ onComplete: function(){ $$('.acordeon_titulo').invoke('observe','click',abrirAcordeon); } }); 
	
}
 
function sendDivFechas(i,a)	{ 
	if ( typeof a != 'undefined' ){
		new Ajax.Request('miColegioPIO.asp?panel=borrarFecha',{ 
			parameters: { 'key' : i },
			onComplete: function(r) { if( r.responseText.indexOf("xxNOHAYSESSIONxx") > -1 ){
				alert('Sr. Usuario: \r\nPor inactividad se ha deslogueado automticamente. \r\nSer redirijido a la pgina');
				window.location.href = './default.asp'; }else actualizarPanel() }
		});
	}else{
		if ( validarTodo() ){ 
			if ( typeof i == 'undefined' ) i = '';
			var param = {
				'key' : i,
				'fecha'  : $F('fecha'), 
				'titulo' : limpiar( $F('titulo') ), 
				'descripcion' : limpiar( $F('descripcion') ) 
			} 
			new Ajax.Request('miColegioPIO.asp?panel=grabarFecha',{
				parameters: param,
				onComplete: mostrarRes
			});
		}else{ 
			alert('Faltan campos'); 
		}
	}
	return false; 
}

function actualizarDatos(){
	if ( grabar() ){
		var datos = $('formRegistro').serialize();
		new Ajax.Request('/formularioAlumnosGrabar.asp',{
			parameters: datos,
			onComplete: function(r) { 
				if ( r.responseText.indexOf('PASSWORD') > -1 ){
					respuesta = r.responseText.split(" ")[1];
					switch(respuesta){
						case 'NO':
							alert("Su contrasea es incorrecta");
							break;
						case 'NCF':
							alert("La confirmacin de la contrasea nueva es incorrecta");
							break;
						case 'OK':
							alert("Su contrasea a sido modificada");
							break;
						case 'CNV':
							alert("Ha ingresado un caracter no valido en la contraseña");
							break;
					}
				}
				actualizarPanel();
			}
		});
	}
}
function descargarArchivo(codigo,event){
	
	var url = "descargar.asp?codigo="+codigo+"&tipo=1";
	var traeData = new uniAjax();
	var respuesta = traeData.leer(url).split("|");
	if ( respuesta[0] == 'OK' ){
		$('textoDivDescarga').innerHTML=respuesta[1];				
		var caja = $('alertaDescarga');
		
		if (window.event) {
			boton=1;
		}else{
			boton=0;
		} //IE	
		var x = event.clientX + getScrollXY()[0];
		var y = event.clientY + getScrollXY()[1];
		$('alertaDescarga').appear({duration:0.5});
		$('alertaDescarga').style.left=x+'px';
		$('alertaDescarga').style.top=y+'px';
	}else{
		alert('Ha ocurrido un error, intente nuevamente');
	}

//	new Ajax.Request('descargar.asp',{ 
//		method: 'GET',
//		parameters: { 'codigo' : codigo, 'tipo' : 1 },
//		onComplete:function(r){
//			var respuesta=r.responseText.split("|");			
//			if ( respuesta[0] == 'OK' ){
//				$('textoDivDescarga').innerHTML=respuesta[1];				
//				var caja = $('alertaDescarga');
//					
//				var x = Event.pointerX(event);
//				var y = Event.pointerY(event);
//				
//				caja.setStyle({
//					left: 	x + 'px',
//					top:	y + 'px'
//				}).appear({duration:0.5});
//				
//			}else{
//				alert('Ha ocurrido un error, intente nuevamente');
//			}
//		}
//	});	
}

function between(int1, int2, int3){
	return ( int2 < int1 ) && ( int3 > int1 )
}

var TOOLTIP = Class.create({
	initialize: function(id, linkClass, url, options){
		// id: ID del elemento contenedor (AREA)
		// linkClass: Elementos que disparan el tooltip
		// url: a llamar por el ajax
		// OPCIONES: 
		//		showTime: El tiempo que tarda en mostrar el contenedor (en segundos)
		//		ajaxOptions: Las opciones de ajax (Ajax.Base) 
		this.options = {
			showTime:	2,
			ajaxOptions: {
				method:       'post',
				asynchronous: true,
				contentType:  'application/x-www-form-urlencoded',
				encoding:     'UTF-8',
				evalJSON:     true,
				evalJS:       true,
				parameters:	  ''
			}
		};
		Object.extend(this.options, options || { });
		
		this.Area = $(id);
		this.Link = $$(linkClass);
		this.AjaxURL = url;
		this.showTime = this.options.showTime * 1000;
	
		this.addBehaviour();
	},
	addBehaviour: function(){
		// Metodo que le los eventos de mouseover y mouseout
		//   a los elementos que matchean con el linkClass
		for ( this.i = 0; this.i <= this.Link.length - 1; this.i ++ ){
			// .bind(this) es para obligar a que tome el metodo de la class y no de window 
			this.Link[this.i]
			  .observe('mouseover',this._show.bind(this) )
				.observe('mouseout',this._hide.bind(this) ); 
		}
	},
	_show: function(e){ // e: Event
		this.Target = Event.element(e);
		Event.stop(e);
		this.tooltipDate = this.Target.href.substr(-10); // La fecha que est al final del link. OJO
		this.update();
		this.locate( this.Target );
		
		setTimeout(	function(){ this.Area.show() }.bind(this), this.showTime );
		setTimeout(	function(){ this.Area.hide() }.bind(this), 10000 );
	},
	_hide: function(e){ // e: Event
		Event.stop(e);
		this.Area.update();
		this.Area.hide();
	},
	update: function(){
		Object.extend(this.options.ajaxOptions, {parameters: {fecha : this.tooltipDate} });
		this.Ajax = new Ajax.Updater(this.Area, this.AjaxURL, this.options.ajaxOptions);
	},
	locate: function(el){ // el = Elemento que disparo el evento
		this.X = el.cumulativeOffset().left + 15;
		this.Y = el.cumulativeOffset().top + 25;
						
		this.windowTotalWidth = this.X + this.Area.getWidth();
		this.windowOriginalWidth = document.viewport.getWidth();
		
		if ( this.windowTotalWidth > this.windowOriginalWidth )
			this.X = el.cumulativeOffset().left - this.Area.getWidth() - 15;
						
		this.Area.setStyle({
			'left'	: this.X + 'px' ,
			'top'	: this.Y + 'px'
		});
	}
});
function reemplazarguionporbarra(campo){
	var valor = campo.value;
	var newValor = replaceChar(valor,"-","/");
	campo.value = newValor;
}
function testearfecha(campoFecha){
	fechaIni = campoFecha.value;
	var errorFecha=false;
	fecha = fechaIni.split("/")
	if (fecha.length > 3 || fecha.length < 3) errorFecha=true;
	if (!parseInt(fecha[0]) || !parseInt(fecha[1]) || !parseInt(fecha[2]) ) errorFecha=true;
	if (!errorFecha){		
		var dia = parseInt(fecha[0]);
		var mes = parseInt(fecha[1]);
		var anio = parseInt(fecha[2]);
		var anioActual = new Date().getFullYear(); 
		if ( dia > 31 ) {
			errorFecha = true;
			mensaje='El da est mal ingresado.';
		}
		if ( mes > 12 ) {
			errorFecha = true;
			mensaje='El mes est mal ingresado.';
		}
		if (anio < 1800 || anio >= anioActual){
			errorFecha = true;
			mensaje='El ao est mal ingresado.';
		}
		if (mes == 2){
		bisiesto = ( anio % 4 == 0 )
			if(bisiesto){
				if( dia > 29 ) {
					errorFecha=true;
					mensaje='El da est mal ingresado.'
				}
			}else{
				if( dia > 28 ) {
					errorFecha=true;
					mensaje='El da est mal ingresado.'
				}
			}
		}else{
			if( mes==1 || mes==3 || mes==5 || mes==7 || mes==8 || mes==10 || mes==12 ){
				if( dia > 31 ) {
					errorFecha=true;
					mensaje='El da est mal ingresado.'
				}
			}else{
				if( dia > 30 ) {
					errorFecha=true;
					mensaje='El da est mal ingresado.'
				}
			}
		}
	}else{
		errorFecha=true;
		mensaje='Respete el formato dd/mm/aaaa.'
	}
	if (errorFecha){
		alert("La fecha es incorrecta. " + mensaje);
		campoFecha.style.color='#FF0000';
	}else{
		campoFecha.style.color='#0060a9';
	}
}
function traerCombos(habilitar,tipo,anio,division){
	if(habilitar=='si'){
		$('enviar').disabled=false;
	}else{
		$('enviar').disabled=true;
		$('comboCarrera').innerHTML = ''
	}
	if (!tipo) return false;
	var url = "../formularioAlumnosGrabar.asp?funcion=traerCombo&tipo="+tipo+"&idAnio="+anio+"&idDivision="+division;
	var traeData = new uniAjax();
	var respuesta = traeData.leer(url);
	switch (tipo){
		case 'carrera':
			$('comboCarrera').innerHTML = respuesta;
			break;
		case 'division':
			$('comboDivision').innerHTML = respuesta;
			break;
	}
}

