﻿if(typeof expandirTarea == 'undefined') expandirTarea=function(){};
NeoGestion = function()
{
	return {
		baseURL : './'
	}
}();

var sendingData=false;
function ajax_navegar(elemento, url)
{
	if(sendingData && url.match(/idtareaX=/)) return false;
	if(url.substring(0,4) != 'http') url= NeoGestion.baseURL+url;
	Cargando.mostrar();
	new Ajax.Updater(elemento, url, {
		evalScripts: true,
		onComplete: function() {
			Cargando.cerrar();
			Element.extend(document.body);
			document.body.scrollTo();
			new Ajax.Updater('tareas_pendientes', NeoGestion.baseURL+'portada_tareas_pendientes.php', { method: 'get', onComplete:expandirTarea });
			// new Ajax.Updater('tareas_recurrentes', NeoGestion.baseURL+'portada_tareas_recurrentes.php', { method: 'get' });
		}
	});
	return false;
}

function ajax_navegar_principal(url)
{
	return ajax_navegar('principal', url);
}

function ajax_enviar_form_sinc(elemento, url, form, elementos, urls, top)
{
	sendingData=true;
	if(url.substring(0,4) != 'http') url= NeoGestion.baseURL+url;
	Cargando.mostrar();
	new Ajax.Updater(elemento, url, {
		parameters: $(form).serialize(),
		evalScripts: true,
		onComplete: function() {
			var ne = elementos.length;
			var nu = urls.length;
			var i = 0;
			if((ne > 0) && (ne == nu))
			{
        for(i=0; i< nu; i++)
          new Ajax.Updater(elementos[i], NeoGestion.baseURL+urls[i], { method: 'get' });
      }
      if(top)
        top.recUsuarios();
      new Ajax.Updater('tareas_pendientes', NeoGestion.baseURL+'portada_tareas_pendientes.php', { method: 'get', onComplete:function(){ sendingData=false; Cargando.cerrar(); expandirTarea(); } });
		}
	});
	return false;
}

function ajax_enviar_form(elemento, url, form, top, url2)
{
	sendingData=true;
	if(url.substring(0,4) != 'http') url= NeoGestion.baseURL+url;
	Cargando.mostrar();
	new Ajax.Updater(elemento, url, {
		parameters: $(form).serialize(),
		evalScripts: true,
		onComplete: function(transport) {
			if(top)
			{
        top.recUsuarios(url2);
        top.cerrar();
			}
			new Ajax.Updater('tareas_pendientes', NeoGestion.baseURL+'portada_tareas_pendientes.php', { method: 'get' , onComplete:function(){ sendingData=false; Cargando.cerrar(); expandirTarea(); } });
			// new Ajax.Updater('tareas_recurrentes', NeoGestion.baseURL+'portada_tareas_recurrentes.php', { method: 'get' });
		}
	});
	return false;
}

function ajax_abrir_dialogo(url, ancho, alto)
{
	Dialogo.mostrar(url, ancho || 800, alto || 400);
	return false;
}

function ajax_valida_fechas(dateini, datefin)
{
	var todobien = "si";
	if (dateini.value.length != 0 && datefin.value.length != 0)
	{
		if (dateini.value > datefin.value)
		{
			todobien = "no";
			alert("La Fecha Inicial No puede ser Mayor a la Fecha Final.!!!");
			return false;
		}
	}

	if (todobien == "si")
	{
		return true;
	}
}





Event.observe(window, 'load', function()
{	
	new Ajax.PeriodicalUpdater('tareas_pendientes', NeoGestion.baseURL+'portada_tareas_pendientes.php', {
		method: 'get',
		frequency: 21600 // Recarga Automatica de Tareas Pendientes cada 21600 Segundos... Es decir cada 6 Horas
	});
	new Ajax.PeriodicalUpdater('tareas_recurrentes', NeoGestion.baseURL+'portada_tareas_recurrentes.php', {
		method: 'get',
		frequency: 600 // Recarga Automatica de Tareas Recurrentes cada 10 Minutos
	});
});


Cargando = function()
{
	var contenedor = document.createElement('div');
	Element.extend(contenedor);
	contenedor.setStyle({
		background: 'url('+NeoGestion.baseURL+'imagenes/reloj.gif) 50% 50%',
		width: 32,
		height: 32,
		position: 'absolute',
		top: 50,
		left: 180,
		
		display: 'none'
	});
	
	Event.observe(window, 'load', function()
	{
		document.body.appendChild(contenedor);
	});

	return {
		mostrar: function()
		{
			contenedor.setStyle({
				background: 'url('+NeoGestion.baseURL+'imagenes/reloj.gif) 50% 50%'
			});
			contenedor.show();
		},
		cerrar: function()
		{
			contenedor.hide();
		}
	};
}();


Dialogo = function()
{
	var ieVersion = (navigator.appVersion.indexOf('MSIE 7') > -1 ? 7 : (navigator.appVersion.indexOf('MSIE 6') > -1 ? 6 : 0));

	var fondo = document.createElement('div');
	Element.extend(fondo);
	fondo.setStyle({
		backgroundColor: '#000',
		height: '100%',
		left: 0,
		position: 'absolute',
		opacity: 0.5,
		top: 0,
		width: '100%',

		display: 'none'
	});

	var exterior = document.createElement('div');
	Element.extend(exterior);
	exterior.setStyle({
		position: 'fixed',
		top: 0,
		left: 0,
		width: '100%',
		height: '100%',

		display: 'none'
	});
	Event.observe(fondo, 'click', function() { exterior.hide(); fondo.hide(); });
	Event.observe(exterior, 'click', function() { exterior.hide(); fondo.hide(); });
	
	var medio = document.createElement('div');
	Element.extend(medio);
	medio.setStyle({
		height: '100%',
		margin: '0 auto'
	});
	exterior.appendChild(medio);

	var interno = document.createElement('div');
	Element.extend(interno);
	interno.setStyle({
		verticalAlign: 'middle'
	});
	medio.appendChild(interno);

	if (!Prototype.Browser.IE)
	{
		medio.setStyle({ display: 'table' });
		interno.setStyle({ display: 'table-cell' });
	}

	var marco = document.createElement('iframe');
	Element.extend(marco);
	marco.src = 'about:blank';
	marco.setStyle({
		backgroundColor: '#FFF',
		border: '1px solid #000',
		textAlign: 'left',
		top: '-50%'
	});
	interno.appendChild(marco);
	
	if (Prototype.Browser.IE && ieVersion <= 7)
	{
		medio.setStyle({
			position: 'absolute',
			top: '50%',
			left: '50%',
			height: 'auto'
		});
		
		interno.setStyle({
			position: 'relative',
			top: '-50%',
			left: '-50%',
			height: 'auto'
		});
	}

	Event.observe(window, 'load', function()
	{
		var body = document.body;
		Element.extend(body);
		var html = body.up();

		if (Prototype.Browser.IE && ieVersion <= 6)
		{
			body.setStyle({
				'overflow-y': 'auto',
				height: '100%'
			});
			
			html.setStyle({
				'overflow-x': 'auto',
				'overflow-y': 'hidden',
				height: '100%'
			});
			
			exterior.setStyle({
				position: 'absolute'
			});
		}

		document.body.appendChild(fondo);
		document.body.appendChild(exterior);
	});

	return {
		mostrar: function(url, ancho, alto)
		{
			if(url.substring(0,4) != 'http') url= NeoGestion.baseURL+url;
			fondo.show();
			fondo.scrollTo();
			marco.src = url;
			marco.setStyle({
				display: 'block',
				width: ancho,
				height: alto
			});
			interno.setStyle({
				width: ancho,
				height: alto
			});
			setTimeout('Dialogo.mostrarTimeout()',0);
		},
		
		mostrarTimeout: function()
		{
			// Si ejecuto la siguiente línea en Dialogo.mostrar(), en algunos
			// browsers, el contenido queda por debajo del fondo.
			exterior.show();
		},
		
		cerrar: function()
		{
			exterior.hide();
			fondo.hide();
			//marco.src = 'about:blank'; Error en Chrome
		},
		
		recargar: function()
		{
			new Ajax.Updater('muestra', 'gnrl_adjuntar_muestra.php', {method: 'get'});
		},
		
		recUsuarios: function(url)
		{
			new Ajax.Updater('usersel', url || 'gnrl_usuarios_muestra.php', {method: 'get'});
		}
	}
}();
/*
container:id contenedor
seek: id campo buscador
seekbd: id campo a buscar
campos: campos a actualizar
*/
Event.observe(document, 'click', function(evt){
	$$('div.neoautocomplete').each(Element.hide);
});
/**
 * Ajax.Request.abort
 * extend the prototype.js Ajax.Request object so that it supports an abort method

Ajax.Request.prototype.abort = function() {
    // prevent and state change callbacks from being issued
    this.transport.onreadystatechange = Prototype.emptyFunction;
    // abort the XHR
    this.transport.abort();
    // update the request counter
    Ajax.activeRequestCount--;
}; */
Array.prototype.inArray = function(valeur) {
	for (var i in this) { if (this[i] === valeur) return i; }
	return -1;
}
var NeoAutoCompleteCookies=Class.create({
	initialize:function(){},
	SetCookie:function (c_name, value, expiredays) {  
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)+	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
	},
	GetCookie:function(nombre) {  
     	if (document.cookie.length>0)
		  {
		  c_start=document.cookie.indexOf(nombre + "=");
		  if (c_start!=-1)
			{
			c_start=c_start + nombre.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
			}
		  }
		return "";
 	}
});
function NeoAutoComplete(id,container,seek,seekbd,table,campos,width,limit,onClear,buscar,guardar,camposcond,tablasaux,where,campostitle) {

	this.htmlseek=null;
	this.autocomplete=null;
	this.selected=false;
	this.width=10;
	this.limit=5;
	this.loading=false;
	this.qcache=[];
	this.buscador=null;
	this.guardarb=null;
	this.onClear=function(){};
	this.buscar={enabled:false,callback:function(){},url:"",w:800,h:600,title:"Escoger...",valor:""};
	this.guardar={enabled:false,callback:function(){},url:"",w:800,h:600,title:"Guardar Nuevo",valor:""};
	this.result={};
	this.camposcond=null;
	this.cookie=null;
	this.create=function(){
		if(document.getElementById(this.seek)){
			this.htmlseek= document.getElementById(this.seek);
			this.container=this.htmlseek.parentNode;
		}else{
			this.htmlseek = document.createElement('input');
			this.htmlseek.type="text";
			this.htmlseek.setAttribute("name",this.seek);
			this.htmlseek.setAttribute("id",this.seek);
			this.htmlseek.setAttribute("size",this.width);
			if(!this.container) this.container=document.body;
		}
		Event.observe(this.htmlseek, 'keyup', this.ajaxSearch.bind(this) );
		Event.observe(this.htmlseek, 'keydown', this.chkEsc.bind(this) );
		Event.observe(this.htmlseek, 'blur', this.chkExist.bind(this) );
		this.htmlseek.setAttribute("autocomplete","off");
		this.htmlseek.setAttribute("title","Digite el valor a buscar");
		this.htmlseek.setAttribute("alt","Digite el valor a buscar");
		this.autocomplete=document.createElement("div");
		this.autocomplete.className="neoautocomplete";
		this.autocomplete.style.width=parseInt(this.width/2) + "em";
		this.autocomplete.style.display="none";
		this.autocomplete.innerHTML='<ul id="'+this.seek+'_data" ></ul>';
		if(!document.getElementById(this.seek)) Element.insert(this.container, { top: this.htmlseek });
		
		//this.autocomplete.style.left=this.findPosX(this.htmlseek) + "px";
//		this.autocomplete.style.left=this.autocomplete.offsetLeft + this.htmlseek.offsetLeft + "px";

//		this.container.appendChild(this.htmlseek);
		if(this.buscar.enabled){
			if(this.buscar.btnId && document.getElementById(this.buscar.btnId)){
				this.buscador=document.getElementById(this.buscar.btnId);
				Event.observe(this.buscador, 'click', function(){ 
						this.selected=true; 
				}.bind(this) );
			}else{
				this.buscador=document.createElement("img");
				this.buscador.src="imagenes/search.gif";
				this.buscador.style.width="17px";
				this.buscador.style.height="17px";
				this.buscador.setAttribute("align","top");
				this.buscador.style.border="1px solid #6699CC";
				this.buscador.style.cursor="pointer";
				this.buscador.onmouseover=function(){ this.style.border="1px solid #000"; }.bind(this.buscador);
				this.buscador.onmouseout=function(){ this.style.border="1px solid #6699CC"; }.bind(this.buscador);
				this.buscador.setAttribute("title",this.buscar.title);
	//			this.buscador.type="button";
				//this.buscador.value=this.buscar.title;
				if( this.buscar.callback){
					Event.observe(this.buscador, 'click', function(){ 
							this.selected=true; 
							return this.buscar.callback.bind(this.buscador)(); 
					}.bind(this) );
				}else {
					Event.observe(this.buscador, 'click', function(){  
							this.selected=true; 
							var campobd=campostitle.split(",");
							var param=(this.buscar.valor !='')?"?"+campobd[0]+"="+this.buscar.valor:"";
							return ajax_abrir_dialogo(this.buscar.url+param, this.buscar.w, this.buscar.h); 
					});
				}
				this.container.appendChild(document.createTextNode(' '));
				this.container.appendChild(this.buscador);
			}
		}
		if(this.guardar  && this.guardar.enabled){
			this.guardarb=document.createElement("img");
			this.guardarb.setAttribute("align","top");
			this.guardarb.style.width="17px";
			this.guardarb.style.height="17px";
			this.guardarb.src="imagenes/save.png";
			this.guardarb.style.border="1px solid #6699CC";
			this.guardarb.style.cursor="pointer";
			this.guardarb.onmouseover=function(){ this.style.border="1px solid #000"; }.bind(this.guardarb);
			this.guardarb.onmouseout=function(){ this.style.border="1px solid #6699CC"; }.bind(this.guardarb);
			this.guardarb.setAttribute("title",this.guardar.title);
			Event.observe(this.guardarb, 'click', function(){ 
				if(this.selected){
					this.htmlseek.value="";
					this.Reset();
				}else{
					if(typeof this.guardar.valor == "undefined" && !this.guardar.modal){
						alert('Digite el valor a guardar');	
					}else{
						try{
							this.guardar.callback(this.guardar.valor);
						}catch(e){}
					}
				}
			}.bind(this));
//			this.buscador.type="button";
			//this.buscador.value=this.buscar.title;
			/*if( this.buscar.callback) Event.observe(this.buscador, 'click', function(){ this.selected=true; return this.buscar.callback.bind(this.buscador)(); }.bind(this) );
			else Event.observe(this.buscador, 'click', function(){  this.selected=true; return ajax_abrir_dialogo(this.buscar.url, this.buscar.w, this.buscar.h); });*/
			this.container.appendChild(document.createTextNode(' '));
			this.container.appendChild(this.guardarb);
		}
		this.container.appendChild(document.createElement("<BR>"));
		this.container.appendChild(this.autocomplete);
	};
	this.ajaxSearch=function(evt){ 
		if(!this.chkEsc(evt)) return;
		
		if(this.selected){
			this.onClear();
			this.Reset();
		}
		this.autocomplete.style.display='none';
		if(this.htmlseek.value==''){
			//this.result=[];
			return;
		}
		var numdata=0;
		var cached=[];
		
		var valoresactuales="";
		for(var j in this.camposcond){
			try{
				valoresactuales+=document.getElementById(j).value+",";
			}catch(e){}
		}
		if(valoresactuales !='') valoresactuales=valoresactuales.substr(0,valoresactuales.length-1);

		for(var i in this.result){
			var obj=this.result[i]; 	
			if(this.camposcond){ 
				if(obj['____FILTER____']!=valoresactuales){
					this.result={};
					this.qcache=[];
					break;
				}
			}else{
				break;	
			}
		}
		
		for(var i in this.result){
			var obj=this.result[i];
		
			var campobd=this.campostitle.split(",");
	
			if(obj[campobd[0]].toLowerCase().indexOf(this.htmlseek.value) == 0 && numdata < this.limit ){
				numdata++;
				cached.push(i);
			}
	  	}
		if(numdata > 0 ){
			if(this.loading) this.loading=false;
			this.renderCache(cached);
			this.autocomplete.style.display="";
		}else{
			this.loading=true;
		}
		if(this.qcache.inArray(this.htmlseek.value) == -1){
			var poststr = "limit="+this.limit+"&seek=" + this.htmlseek.value+"&seekbd="+this.seekbd+"&table="+this.table+"&rnd="+Math.random();
			poststr+="&campos="+this.seekbd+",";
			for(var i in this.campos){
				poststr +=this.campos[i]+",";	
			}
			poststr=poststr.substr(0,poststr.length-1);
			poststr+="&campostitle="+this.campostitle;
			if(this.camposcond){
				poststr+="&wheref=";
				for(var i in this.camposcond){
					poststr+=this.camposcond[i]+",";
				}
				poststr=poststr.substr(0,poststr.length-1);
				poststr+="&wherev=";
				for(var i in this.camposcond){
					try{
						poststr+=document.getElementById(i).value+",";
					}catch(e){}
				}
				poststr=poststr.substr(0,poststr.length-1);
			}
			if(this.tablasaux){
				poststr+="&tablasaux="+this.tablasaux;
			}
			if(this.where){
				poststr+="&wherestr="+this.where;
			}
			this.request = new Ajax.Request('neoautocomplete.php', {method: 'get', parameters:poststr, onSuccess:this.render.bind(this) });
		}
	};
	this.findPosX=function(obj){
	    var curleft = 0;
    	if(obj.offsetParent){
	        while(1) {
        	  curleft += obj.offsetLeft;
	          if(!obj.offsetParent)  break;
	          obj = obj.offsetParent;
    	    }
		}else if(obj.x)curleft += obj.x;
	    return curleft;
	};
	this.chkEsc=function(evt){ 	
		var evento = evt || window.event;
		var key = evento.keyCode;
		if (key==27 || key==9 ) {
			this.autocomplete.style.display='none';
			return false;
		}else return true;
	};
	this.renderCache=function(cached){
		var data=$(this.seek+'_data');
		data.innerHTML="";
		for(var i=0;i<cached.length;i++){
			var obj=this.result[cached[i]];
			var li=document.createElement('li');
			var campobd=this.campostitle.split(",");
			li.innerHTML=obj[campobd[0]];
			li.onclick=this.load.bind(this,cached[i]);
			li.onmouseover=function(){
				this.style.backgroundColor="#ccc";
			}
			li.onmouseout=function(){
				this.style.backgroundColor="#fff";
			}
			$(this.seek+'_data').appendChild(li);
		}
	};
	this.render=function(http_request){
		if(this.loading){
			var data=$(this.seek+'_data');
			data.innerHTML="";
		}
		var result = eval(http_request.responseText);
		for(var i=0;i<result.length;i++){
			var campobd=this.campostitle.split(",");
			this.result[result[i][campobd[0]]]=result[i];
			if(this.loading){
				var li=document.createElement('li');
				li.innerHTML=result[i][campobd[0]];
				li.onclick=this.load.bind(this,result[i][campobd[0]]);
				li.onmouseover=function(){
					this.style.backgroundColor="#ccc";
				}
				li.onmouseout=function(){
					this.style.backgroundColor="#fff";
				}
				$(this.seek+'_data').appendChild(li);
			}
		}
		if(this.loading && result.length>0){
			if(this.qcache.length==50) this.qcache[this.qcache.length-1]=this.htmlseek.value;
			else this.qcache.push(this.htmlseek.value);

			this.autocomplete.style.display="";
			var valorcookie="[";
			var k=0;
/*			for(var i in this.result){
				if(k==50) break;
				k++;
				valorcookie+="{";
				var obj=this.result[i];
				for(var j in obj){
					valorcookie+="'"+j+"':'"+obj[j]+"',";
				}
				valorcookie=valorcookie.substr(0,valorcookie.length-1);
				valorcookie+="},";
			}
			if(valorcookie.length > 1) valorcookie=valorcookie.substr(0,valorcookie.length-1);*/
			valorcookie+="]";
			this.cookie.SetCookie(this.id,valorcookie);
		}
		this.loading=false;
	};
	this.load=function(index){
		for(var i in this.campos){
			try{
				document.getElementById(i).value=this.result[index][this.campos[i]];
			}catch(e){}
		}
		var campobd=this.campostitle.split(",");
		this.htmlseek.value=this.result[index][campobd[0]];
		this.selected=true;
		this.autocomplete.style.display='none';
	};
	this.chkExist=function(){
		if(!this.selected){
			if(this.buscar.enabled){
				this.buscar.valor= this.htmlseek.value;
			}

			if(this.guardar.enabled){
				this.guardar.valor=	this.htmlseek.value;
			}
			this.htmlseek.value="";
this.Reset();
		}
	};
	this.Reset=function(){
		for(var i in this.campos){
			try{
				document.getElementById(i).value="";
			}catch(e){}
		}
		this.selected=false;
	}
	
	this.id=id;
	this.seek=seek;
	this.seekbd=seekbd;
	this.table=table;
	this.campos=campos;
	if(width)this.width=width;
	if(limit)this.limit=limit;
	if(buscar)this.buscar=buscar;
	if(guardar)this.guardar=guardar;
	if(onClear)this.onClear=onClear;
	if(camposcond)this.camposcond=camposcond;
	if(tablasaux)this.tablasaux=tablasaux;
	if(where)this.where=where;
	this.campostitle=campostitle;
	this.container=document.getElementById(container);
	this.create();
	this.cookie=new NeoAutoCompleteCookies();
	if(this.cookie.GetCookie(this.id) != ''){
		var result = eval(this.cookie.GetCookie(this.id));
		var campobd=this.campostitle.split(",");
		for(var i=0;i<result.length;i++){
			this.result[result[i][campobd[0]]]=result[i];
			var li=document.createElement('li');
			li.innerHTML=result[i][campobd[0]];
			li.onclick=this.load.bind(this,result[i][campobd[0]]);
			li.onmouseover=function(){
				this.style.backgroundColor="#ccc";
			}
			li.onmouseout=function(){
				this.style.backgroundColor="#fff";
			}
			$(this.seek+'_data').appendChild(li);
		}	
	}
};


