//
//  Copyright 2001 (c) Ismael Canales Luis.
//

window.onerror=void(0)


function addBookmark(str){
str=document.title;
if (document.all)window.external.AddFavorite(document.location.href,str)
else if( window.sidebar.addPanel)window.sidebar.addPanel(str,document.location.href,'')
else alert('Por vavor pulse CTRL+D, este navegador no es compatible con esta funciÃ³n.\n');
}

	function hide(on,layer){
		layer=get(layer)
		if( ! layer ) return;
		if( on >0 ){
			layer.style.visibility='inherit'
		}else{
			layer.style.visibility='hidden'
		}

	}

	function confirmJump(jump,text){
		ret=confirm(text)
		if(ret){
			document.location.href=jump
			return true;
		}
		return false;
	}

	function openWindow(url,name,width,height){
		win=window.open(url,name,"location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes");
		if(win){
			center_window(win);
			win.focus();
		}
		return win;
	}

	function openBrowser(url,name,width,height){
		win=window.open(url,name,"height="+height+",width="+width+",toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes");
		if(win){
			center_window(win);
			win.focus();
		}
		return void(0);
	}

	function set_form_jump(form,jump,url)
	{
		form.jump.value=jump; 
		//form.action=url;
	}


	function pop(url){
		window.open(url,'_blank',"location=no,resizable=yes,scrollbars=no,status=no,menubar=no")
	}


	unique = null;
	function openDialog(url,width,height){
		try{
			unique.close()
		}catch(e){
		}
		unique=window.open(url,'unique',"height="+height+",width="+width+",location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes")
		if( unique){
			center_window(unique);
			unique.focus();
		}
		return unique;
	}

	function _openDialog(url,width,height){
		w=window.open(url,'_blank',"height="+height+",width="+width+",location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes")
		if( w){
			center_window(w);
			w.focus();
		}
		return w;
	}

	function swap_background(object,image){
		object.background=image	
	}

	function findFormField(name,form)
	{
		var i;
		for ( i=0 ; i < form.length ; i++) {
			if( form[i].name == name){
				return form[i];
			}
		}
		return false;
	}

	/*
	function set_form_date_value(formNumber,nameField,year,month,day){

		form= opener.document.forms[formNumber];
		
		oy=findFormField(nameField+'[year]',form.elements);	
		find_and_select_value(oy,year);
		
		om=findFormField(nameField+'[month]',form.elements);	
		find_and_select_value(om,month);

		od=findFormField(nameField+'[day]',form.elements);	
		find_and_select_value(od,day);

	}

	function get_form_date(form,nameField){

		oy=findFormField(nameField+'[year]',form.elements);	
		oy=oy.options[oy.selectedIndex].value;
		
		om=findFormField(nameField+'[month]',form.elements);	
		om=om.options[om.selectedIndex].value;

		od=findFormField(nameField+'[day]',form.elements);	
		od=od.options[od.selectedIndex].value;

		return oy+'-'+om+'-'+oy ;
	}
	*/

	
	function find_and_select_value(field,value){
		var a=0;
		var finded=0;
		for(i=0;i<field.options.length;i++){
			if(field.options[i].value==value){
				if( i != 0){	
					field.selectedIndex=i;
					return i;			
				}else{
					a=1;
				}
			}
		}

		if(a){
			field.selectedIndex=0;
		}else{
			opt=new Option();
			opt.value=value;
			opt.text=value;
			opt.selected=true;
			field.options[field.options.length]=opt;
			field.selectedIndex=field.options.length-1;
		}
		
		return -1;
	}

	function center_window(win)
	{
		/*
		win.self.screenX=(self.screen.height-win.outerHeight)/2
		win.self.screenY=(self.screen.width-win.outerWidth)/2
		*/
	}





function go(url){document.location.href=url}

function debug(msg)
{
	obj=get('debug')
	obj=null
	if(obj){
		obj.innerHTML+=msg;
		obj.innerHTML+="<br>";
	}
	return msg;
}

function get(id) { return document.getElementById(id); }


function check_date(date,msgfail)
{
	if( date=="" ){
		return 1;
	}
	d=date.split('/')
	d[0]=parseInt(d[0],10)
	d[1]=parseInt(d[1],10)
	d[2]=parseInt(d[2],10)
	dm=new Array(0,31,28,31,30,31,30,31,31,30,31,30,31)
	m=""
	if(d[1]>=1 && d[1]<=12){
		dia=dm[d[1]]
		if(d[0]<=dia && d[0]>=1 ){
			if(d[2]>0){
				return 1;
			}
		}
	}
	if(msgfail)alert(msgfail)
	return 0;
}


function check_time(time,msgfail)
{
	if( time=="" ){
		return 1;
	}
	d=date.split(':')
	d[0]=parseInt(d[0],10)
	d[1]=parseInt(d[1],10)
	d[2]=parseInt(d[2],10)
	if(d[0]>=0 && d[0]<24){
		if(d[1]<60 && d[1]>=0 ){
			if(d[2]<60 && d[2]>=0 ){
				return 1;
			}
		}
	}
	if(msgfail)alert(msgfail)
	return 0;
}



function current_date()
{
	var today = new Date()
	var year = today.getYear()
	if(year<1000) year+=1900
	return today.getDate() + "/" + 	(today.getMonth()+1) + "/" + (year+"").substring(2,4)
}


function current_time()
{
 curDateTime = new Date()
 curHour = curDateTime.getHours()
 curMin = curDateTime.getMinutes()
 curSec = curDateTime.getSeconds()
 return ((curHour < 10) ? "0" : "") + curHour + ":" 
	        + ((curMin < 10) ? "0" : "") + curMin + ":" 
		    + ((curSec < 10) ? "0" : "") + curSec 
}


function f_calendar_onclick(field_id,url,msgfail)
{
	o=get(field_id);
	value=o.value
	ok=check_date(value)
	if( value=="" || ok==0 ){
		d=new Date();
		value=current_date();
	}
	if(!ok){alert(msgfail)}
	win=_openDialog(url+'&date='+value+'&field_id='+field_id,320,200);
	win.druida_date_field=o;
	return 1;
}

/*  Atencion borra los onInit una vez ejecutados de manera que puede llamarse 100 veces si hace falta */
/* parece que interacciona mal con algun otro js */
function runOnInit(){
	tags= new Array('form','div','span','a','input','select');
	for(j=0;j<tags.length;j++){
		f=document.getElementsByTagName(tags[j]);	
		for(i=0;i<f.length;i++){
			js=f[i].getAttribute("onInit");
			if( js ){
				try{
					ok=eval(js);
				}catch(e){
					debug("runOnInit: "+e)
				}
				js=f[i].setAttribute("onInit",null);
			}

		}
	}
}


function drEventHandler(name)
{
	this.handler=new Array()
	this.push=_add
	this.run=_run
	this.id=0
	this.name=name


	function _add(new_handler)
	{
		this.handler.push(new_handler)
		this.id++;
		return this.id;
	}


	function _run()
	{
		// si un solo handler da false damos false
		// pero seguimos ejecutandolos, humm
		ok=true;
			for(i=0;i<this.handler.length;i++){
			//	try{
					//alert(this.name+i+":"+this.handler[i])
					ok=this.handler[i]()
			//	}catch(e){
					//alert("Error handler "+this.name+" "+e);
			//	}
			}
		return ok;
	}
}

window.onload_manager=new drEventHandler("onload")
window.onload_manager.push(runOnInit);
window.onload=new Function("window.onload_manager.run();");

window.onresize_manager=new drEventHandler("onresize")
window.onresize=new Function("window.onresize_manager.run();");

window.onscroll_manager=new drEventHandler("onscroll")
window.onscroll=new Function("this.onscroll_manager.run();");

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


function floatingPanel(container_id,content_id,tableprefix)
{
	this.counter=0;
	this.x0=0;
	this.container=get(container_id);
	this.content=get(content_id);
	this.tableprefix=tableprefix;
	this.table=get(tableprefix)
	this.move=move;
	this.recalculate=recalculate;
	this.animate=animate
	this.animate_one=animate_one
	this.calculated=0;
	this.td=null;
	this.repos=repos;

	function move(step)
	{
		if( this.calculated==0) return;
		try{
			obj=this.content
			if(step>0){
				if(!get(this.tableprefix+(this.counter+1))){
					return
				}
				this.td=get(this.tableprefix+this.counter)
			}else{
				this.td=document.getElementById(this.tableprefix+(this.counter-1))
			}
			if(this.td){
				mov=this.td.clientWidth
				pos=findPos(obj)
				x=pos[0]-step*mov-this.x0
				debug("pos:"+pos[0]+"  step: "+mov+" finalpos:"+x);
				this.counter+=step;
				//this.content.style.left=x;
				this.animate(x,x-(pos[0]-this.x0),0.5)
			}
		}catch(e){
			debug(e)
		}
	}

	function animate_one()
	{
		debug("animate one "+this.pasos+" "+this.frames)
		if(this.pasos<=this.frames){
			if(this.pasos==this.frames)mov=this.pos_final
			else	mov=this.inicial+this.paso*this.pasos;
			debug("moving "+mov)
			pos=findPos(this.content)
			this.content.style.left=mov;
			this.pasos++;
		}else{
			debug("clear")
			clearInterval(this.timer)
			this.moving=0
			this.repos()
		}
	}

	function animate(final,distancia,time)
	{
		debug(" final "+final+" distancia "+distancia+" time "+time);
		this.moving=1
		fs=16
		this.frames=time*fs;	
		debug(this.frames);
		this.paso=distancia / this.frames;
		this.pasos=0;
		this.inicial=final-distancia
		this.pos_final=final;
		debug("frames="+this.frames+" delta="+this.paso)
		window.animate=this
		this.timer=setInterval("window.animate.animate_one()",time*1000/fs);
	}


	function recalculate(){
		pos=findPos(this.content)
		i=0;
		this.max=0;
		this.x0=pos[0];
		this.calculated=1
		debug("COUJNTER: "+this.counter)
		debug(this.tableprefix+0)
		debug(get(this.tableprefix+0).clientWidth)
		//this.container.style.height=this.content.clientHeight // adjusting the height
		//alert(this.content.clientHeight);
		//this.content.style.position="absolute"
		//this.container.style.position="relative"
	}

	function repos(){
		//this.container.style.height=get(this.tableprefix+this.counter).clientHeight // adjusting the height
		this.container.style.width=get(this.tableprefix+this.counter).clientWidth;
	}
}

function adiv(refobj,id,content,clase)
{
	refobj=get(refobj)
	refobj.innerHTML+='<div id="'+id+'"style="position:absolute;z-index:2;" class="'+clase+'">'+content+'</div>';
	pos=findPos(refobj)
	o=get(id)
	o.style.left=pos[0]
	o.style.top=pos[1]
}


function console()
{
	document.write("<div style=\"border-color: black; width:100% ; height=400pxs;\" id=debug ></div>")
}


function flip(id,force,load){
	o=get(id)
	if(o){
		if(o.style.visibility!='hidden' || force==0){
			o.style.visibility="hidden";
			o.style.position="absolute";	
			o.style.display="none";
		}else{
			o.style.visibility="inherit";
			o.style.position="relative";	
			o.style.display="inline";
			if(load){
				load(id);	
			}
		}
	}
}



function flipload_hide(id){
		o.style.visibility="hidden";
/*		o.style.position="absolute";	
		o.style.display="none";*/
}

function flipload(id,url,operacion){
	if(!operacion){
		operacion='set_html';
	}
	o=get(id)
	if(o){
		o.style.visibility="visible";
/*
		o.style.position="relative";	
		o.style.display="inline";
*/
		ajump(url,id,operacion);
	}
}


function ajax(){

	this.print=print
	this.get=get
	this.post=post
	this.wget=wget
	this.onEndRequest=onEndRequest
	this.push=push_html;
	this.pop=pop_html;


	function push_html(id)
	{
		o=document.getElementById(id)
		if(o){
			try{
				o.cache.push(o.innerHTML);
			}catch(e){
				o.cache=new Array();
				o.cache.push(o.innerHTML);
			}
		}
	}


	function pop_html(id)
	{
		o=document.getElementById(id)
		if(o){
			try{
				o.innerHTML=o.cache.pop();
			}catch(e){
			}
		}
	}




	function onEndRequest(status,content){
		return 0+1;	
	}	


	function print(msg,object_id,operation)
	{
	//	if(operation == 'set_html' || operation==null){
				obj=document.getElementById(object_id);
				if(obj)
					obj.innerHTML='<span style="font-face:arial; font-size: 12px; color: white; background-color: red">'+msg+'</span><br>'+obj.innerHTML;
	//	}

	}


	// no funciona  es asincrono el ajax automelon xDDD
	function wget (url) {

		this.req=false

		this.wget_ok=false

		// Constructor
		if (this.req==false) {
			if (window.XMLHttpRequest) {
				try {
					this.req=new XMLHttpRequest()
				} catch (e) {
					this.req=false
				}
			} else if (window.ActiveXObject) {
				try {
					this.req=new ActiveXObject("Msxml2.XMLHTTP")
				} catch (e) {
					try {
						this.req=new ActiveXObject("Microsoft.XMLHTTP")
					} catch (e) {
						this.req=false
					}
				}
			}

			if (this.req) {
				var request=this.req
				// Se llama cuando se recibe una respuesta y la procesa
				this.req.onreadystatechange=function () {
					// Cuando me llamen porque ya esta cargada la respuesta
					if (request.readyState==4) {
						// Si todo fue bien...
						if (request.status!=200) {	// OK
							alert(request.status+': No se ha podido acceder a la url "'+url+'"')
						}else{
							this.wget_ok=true
						}
					}
				}
				if(this.wget_ok){
					return this.request.responseText;
				}
				// Envia la peticion
				this.req.open("GET",url,true)
				this.req.send(null)
			} else {
				alert("Ajax not supported")
			}
		}
	}

	// Ajax: Recibe un fichero remoto en el que hacer la peticion, y una cadena de parametros GET
	// Hace una llamada a la 'url', y cambia el contenido del objeto 'object_id' aplicando la accion 'operation'
	function get (url,object_id,operation) {

		this.req=false

		if(operation == ''){
			operation='set_html';
		}

		// Constructor
		if (this.req==false) {
			if (window.XMLHttpRequest) {
				try {
					this.req=new XMLHttpRequest()
				} catch (e) {
					alert(e);
					this.req=false
				}
			} else if (window.ActiveXObject) {
				try {
					this.req=new ActiveXObject("Msxml2.XMLHTTP")
				} catch (e) {
					try {
						this.req=new ActiveXObject("Microsoft.XMLHTTP")
					} catch (e) {
						this.req=false
					}
				}
			}

			if (this.req) {
				var request=this.req
				var oer=this.onEndRequest;
				this.req.onreadystatechange=function () {
					// Cuando me llamen porque ya esta cargada la respuesta
					if (request.readyState==4) {
						// Si todo fue bien...
						if (request.status==200) {	// OK
							try {
								// Sustituye el contenido en el objeto 'object_id', realizando la accion 'operation'
								refreshHTMLContent(request.responseText,object_id,operation,url)
							
							} catch (e) {
								alert('El contenido del id "'+object_id+'" no se pudo actualizar')
								alert('Error al procesar la respuesta de ajax '+e)
								//alert('El contenido de la respuesta es\n'+request.responseText)
							}
							oer(request.status,request.responseText);
						} else {
							alert(request.status+': No se ha podido acceder a la url "'+url+'"')
						}

						//document.getElementsByTagName('body')[0].style.cursor='default';
					}
				}
				// Envia la peticion
				this.req.open("GET",url,true)
				this.req.send(null)
				if(operation!="append")
				this.print("Cargando...",object_id,operation);
			} else {
				alert("Ajax not supported")
			}
		}
	}

	function post (url,object_id,f,operation) {

			if(operation == ''){
				operation='set_html';
			}
			this.req=false;

			if (window.XMLHttpRequest) {
				try {
					this.req=new XMLHttpRequest()
				} catch (e) {
					this.req=false
				}
			} else if (window.ActiveXObject) {
				try {
					this.req=new ActiveXObject("Msxml2.XMLHTTP")
				} catch (e) {
					try {
						this.req=new ActiveXObject("Microsoft.XMLHTTP")
					} catch (e) {
						this.req=false
					}
				}
			}

			if (this.req) {
				var request=this.req
				// Se llama cuando se recibe una respuesta y la procesa
				
				var oer=this.onEndRequest;
				this.req.onreadystatechange=function () {
					// Cuando me llamen porque ya esta cargada la respuesta
					if (request.readyState==4) {
						// Si todo fue bien...
						if (request.status==200) {	// OK
							try {
								// Sustituye el contenido en el objeto 'object_id', realizando la accion 'operation'
								refreshHTMLContent(request.responseText,object_id,operation,url)
								oer(request.status,request.responseText);
							} catch (e) {
								alert('El contenido del id "'+object_id+'" no se pudo actualizar')
								alert('Error al procesar la respuesta de ajax '+e)
								//alert('El contenido de la respuesta es\n'+request.responseText)
							}
						} else {
							alert('No se ha podido acceder a la url "'+url+'" para hacer la peticion code='+request.status)
						}
					}else{

					}
				}

				// Envia la peticion
				parameters="";
				if(f.elements != null){

					for(i=0;i<f.elements.length;i++){
						try{
							type=f.elements[i].type.toUpperCase();
							if( type == 'SELECT'){
								val=f.elements[i].options[f.elements[i].selectedIndex].value
							}else if ( type == 'CHECKBOX'){
								val=f.elements[i].checked ? f.elements[i].value : null
							}else if ( type == 'RADIOBUTTON'){
								if(f.elements[i].checked){
									val=f.elements[i].value;
								}else continue;
							}else if (type == 'BUTTON' || type=='IMAGE'){
								continue;
							}else{
								val=f.elements[i].value;
							}	
							parameters+=encodeURI(f.elements[i].name)+'='+encodeURI(val)+"&";
						}catch(e){
							alert(e)
						}
						
					}
				}else{
					for(key in f){
						try{
							parameters+=encodeURI(key)+'='+encodeURI(f[key])+"&";
						}catch(e){
							alert(e)
						}
					}
				}
				this.req.open('POST', url, true);
				url=url+'?'+parameters
				this.req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				this.req.setRequestHeader("Content-length", parameters.length);
				this.req.setRequestHeader("Connection", "close");
				this.req.send(parameters);
				this.print("Conectando...",object_id,operation);
				
			} else {
				alert("Ajax not supported")
			}
	}


	this.encodePart=function (name,value){
		return "--AaB03x123ssdd\nContent-Disposition: form-data; name="+name+"\n\n"+value+"\n";

	}


	this.post2=function(url,object_id,f,operation) {

			if(operation == ''){
				operation='set_html';
			}
			this.req=false;

			if (window.XMLHttpRequest) {
				try {
					this.req=new XMLHttpRequest()
				} catch (e) {
					this.req=false
				}
			} else if (window.ActiveXObject) {
				try {
					this.req=new ActiveXObject("Msxml2.XMLHTTP")
				} catch (e) {
					try {
						this.req=new ActiveXObject("Microsoft.XMLHTTP")
					} catch (e) {
						this.req=false
					}
				}
			}



			if (this.req) {
				var request=this.req
				// Se llama cuando se recibe una respuesta y la procesa
				
				var oer=this.onEndRequest;
				this.req.onreadystatechange=function () {
					// Cuando me llamen porque ya esta cargada la respuesta
					if (request.readyState==4) {
						// Si todo fue bien...
						if (request.status==200) {	// OK
							try {
								// Sustituye el contenido en el objeto 'object_id', realizando la accion 'operation'
								refreshHTMLContent(request.responseText,object_id,operation,url)
								oer(request.status,request.responseText);
							} catch (e) {
								alert('El contenido del id "'+object_id+'" no se pudo actualizar')
								alert('Error al procesar la respuesta de ajax '+e)
								//alert('El contenido de la respuesta es\n'+request.responseText)
							}
						} else {
							alert('No se ha podido acceder a la url "'+url+'" para hacer la peticion code='+request.status)
						}
					}else{

					}
				}

				// Envia la peticion
  				parameters="Content-Type: multipart/form-data; boundary=AaB03x123ssdd\n\n";
                                if(f.elements != null){

                                        for(i=0;i<f.elements.length;i++){
                                                try{
                                                        type=f.elements[i].type.toUpperCase();
                                                        if( type == 'SELECT'){
                                                                val=f.elements[i].options[f.elements[i].selectedIndex].value
                                                        }else if ( type == 'CHECKBOX'){
                                                                val=f.elements[i].checked ? f.elements[i].value : null
                                                        }else if ( type == 'RADIOBUTTON'){
                                                                if(f.elements[i].checked){
                                                                        val=f.elements[i].value;
                                                                }else continue;
                                                        }else if (type == 'BUTTON' || type=='IMAGE'){
                                                                continue;
                                                        }else{
                                                                val=f.elements[i].value;
                                                        }
                                                        parameters+=this.encodePart(f.elements[i].name,val);
                                                }catch(e){
                                                        alert(e)
                                                }

                                        }
                                }else{
                                        for(key in f){
                                                try{
                                                        parameters+=this.encodePart(key,f[key]);
                                                }catch(e){
                                                        alert(e)
                                                }
                                        }
                                }
                                parameters+="--AaB03x123ssdd--\n";
				this.req.open('POST', url, true);
				this.req.setRequestHeader("Content-type", "multipart/form-data; boundary=AaB03x123ssdd");
				this.req.setRequestHeader("Content-length", parameters.length);
				this.req.setRequestHeader("Connection", "close");
				this.req.send(parameters);
				this.print("Conectando...",object_id,operation);
				
			} else {
				alert("Ajax not supported")
			}
	}



}






// Realiza una accion sobre un objeto html
// 	- content puede ser html, javascript, o un valor, etc (lo que vayamos a cambiar)
//	- object_id define el objeto sobre el que va a actuar la operacion
// 	- operation define la operacion a realizar sobre el objeto 'object_id', por defecto, la operacion es 'set_value'
//		Tipos de operaciones:
//			- set_value
//			- set_html
//			- funcion javascript con los parametros (id, value)

function ajump(url,container_id,handler,observer)
{
	a= new ajax()
	a.push(container_id)
	if(observer)
		a.onEndRequest=observer
	a.get(url,container_id,handler)
}


function wget(url)
{
	a= new ajax()
	return a.wget(url)
}

function apost(url,object_id,operation,f) {

	a= new ajax()
	a.push(object_id)
	a.post2(url,object_id,f,operation)
}

function ajax_pop(id)
{
	a=new ajax()
	a.pop(id)
}

function ajax_clean(id)
{
	o=get(id);
	o.cache=new Array()
	o.innerHTML="";
}




function refreshHTMLContent (content,object_id,operation,url)
{
	var result=true


	// Default operation
	if (operation==null || operation=='') {
		if( object_id == null || object_id == ''){
			operation='just_call'
		}else{
			operation='set_value'
		}
	}


	flag_eval=0;

	var js_code="";
	
	if( content.match(/<script.*?>/)){
		try{
			var cont=js_parser(content);
			js_code=cont[1];
			content=cont[0];
			flag_eval=1;
		}catch(e){
			alert("Error evaluando javascript (js_parser):\n"+js_code+e);
		}
	}else{
		try{	// sistema antiguo por json perro
			content=eval(content);	
			js_code=content[1]
			flag_eval=1;
			content=content[0];
		}catch(e){  // parser de <script>
		}
	}

	switch (operation) {
	// Para campos de formularios, establece el valor del campo
		case 'set_value':
			setObjectValue(object_id,content)
			break

		case 'call':
			// operacion call, no cambia ningun inner ni nada de la pagina
			break;

		case 'reload':
			window.document.location.href=window.document.location.href
			break;

		case 'reload_opener':
			opener.document.location.href=opener.document.location.href
			break;

		case 'append':
			var obj=document.getElementById(object_id)
			obj.ajax_url=url
			if(!content)content="";
			obj.innerHTML+=content
			break;

		case '':
		case 'set_html':
			var obj=document.getElementById(object_id)
			if(obj){
				obj.ajax_url=url
				if(!content)content="";
				obj.innerHTML=content;
			}
			break

		default:
			operation()
			break;
	}

	if( flag_eval ){
			kk=eval(js_code);	
	}
	return content
}

function getElementsByPrefix(id){
	ids=new Array();
	i=0;
	a=id+i
	o=get(id+i);
	while(o){
		ids[i]=o
		i++;
		o=get(id+i);
	}
	return ids;
}



function js_parser(content)
{
	code="";
	rgx= new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)','img');	
	m=rgx.exec(content);
	while(m!=null){
		code= code + ";" + m[1];
		rgx= new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)','img');	
		m=rgx.exec(RegExp.rightContext);
	}
	return new Array(content,code);
}

// Función genérica para establecer un value para campos de formulario, y otros casos especiales
// Se pueden añadir funcionalidades sin problema
function setObjectValue (id,value)
{
	var obj=document.getElementById(id)
		
	// Para campos de formulario (con tipo)
	if (obj.type && value!=null) {
		// Es un input, le ponemos el value
		if (obj.type=='text' || obj.type=='password') {
			obj.value=value
		// Es un checkbox
		} else if (obj.type=='checkbox') {
			if (value.length>0 && value!='0' && value!='false') {
				obj.checked=true
			} else {
				obj.checked=false
			}
		// Para selectores (por ahora no distingue entre simple o multiple)
		} else if (obj.selectedIndex!=null) {
			i=0
			while (i<obj.options.length) {
				if (obj.options[i].value==value) {
					obj.selectedIndex=i
					break
				}
				i++
			}
		// Tipo desconocido
		} else {
			alert('setObjectValue: Tipo desconocido del campo de tipo ('+obj.type+')')
		}
	// Para otros tags
	} else if (obj.tagName && value!=null) {

		// Tipo imagen (cambiamos el src de la imagen)
		if (obj.tagName=='IMG') {
			obj.src=value
		// Una capa, cambiamos el innerHTML
		}else if( obj.innerHTML ){
			obj.innerHTML=value
		} else {
			alert('setObjectValue: Funcion no definida para el objeto ('+obj.tagName+')')
		}
	}
}


function Validator(form)
{
	self.required=required
	self.integerRange=integerRange
	self.email=email
	self.is_date=is_date


	for(i=0;i<form.elements.length;i++){
		if( form.elements[i].validate ){
			specs=eval(form.elements[i].validate)
			funct = specs[i][0]
			id_field=form.elements[i].id
			msg   = specs[i][2]
			parms = specs[i][3]
			try{
				hola=eval(funct+"()")
			}catch(e){
				alert(msg);
				return false;
			}
		}
	}

}

function set_cookie (name, value) {
	var argv = setcookie.arguments;
	var argc = setcookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
	((expires == null) ? "" : ("; expires=" + expires.togmtstring())) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == true) ? "; secure" : "");
}



function signal(destination_pair)
{
	ret=void(0);
	a=destination_pair.split('.')
	dest=get(a[0])
	if(dest ){		
		handler=dest.getAttribute(a[1]);
		if(!handler){  
			alert("signal call "+destination_pair+", handler not found");
		}else{
			try {
				eval(handler);
			}catch(e){
				alert("signal call "+destination_pair+", "+e);
					
			}
		}

	}else{
		alert("signal call "+destination_pair+" failed");
	}
	return ret;
}


function writeIframe (p) {
		var h = '', n;

		h += '<iframe ';
		h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : '';
		h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : '';
		h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : '';
		h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : '';
		h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : '';
		h += typeof(p.mce_src) != "undefined" ? 'src="' + p.mce_src + '"' : '';
		h += typeof(p.marginwidth) != "undefined" ? 'marginwidth="' + p.marginwidth + '"' : '';
		h += typeof(p.marginheight) != "undefined" ? 'marginheight="' + p.marginheight + '"' : '';
		h += typeof(p.frameborder) != "undefined" ? 'frameborder="' + p.frameborder + '"' : '';
		h += typeof(p.scrolling) != "undefined" ? 'scrolling="' + p.scrolling + '"' : '';
		h += '>Necesitas iframes!!</iframe>';
		document.write(h);
}



function mceEditorOnSubmit(id,form)
{
	o= get('mce_editor_check_'+id);
	if(o && o.checked==false ){ 
		tinyMCE.execCommand('mceToggleEditor',false,'mce_editor_'+id) 
		tinyMCE.execCommand('mceToggleEditor',false,'mce_editor_'+id) 
	}
	fieldname=o.value
	inst = tinyMCE.getInstanceById('mce_editor_'+id);
	if(inst && form && form[fieldname]){
		form[fieldname].value=inst.getHTML();
		return true;
	}
	return false;
}

/*
function myCalendar(field)
{

	function onSelect(calendar, date) {
	    field.value = date;
	    if (calendar.dateClicked) {
	        calendar.callCloseHandler(); 
	    }
	};

	function onClose(calendar) {
	  calendar.hide();
	    // or calendar.destroy();

	this = new Calendar(1,field.value,onSelect,onClose)
	this.setDateFormat("%d/%m/%y");
	this.parseDate(field.value);
	this.showAtElement(field,"right");
	this.create()
}
*/



