function popUp(direccion,ancho,alto,iframe){
  if(iframe){
	var w;
    if(window.parent){
        w=window.parent;
    }else{
        w=window;  
    }
	try{
		w.$('popUpIframe').remove();
		w.$('cerrar_popUpIframe').remove();
	}catch(ex){}
    ocultarFlash(w);
    var alto_ventana=w.getHeight();
    var scroll_ventana=w.getScrollTop();
    
    var fondo=w.document.createElement('div');
    fondo.id='fondo_popup';
    w.document.getElementsByTagName('body')[0].appendChild(fondo); 
    fondo.style.width=w.Window.getScrollWidth()+'px';   
    fondo.style.height=w.Window.getScrollHeight()+'px';
    
    var pos_y=Math.round((alto_ventana-alto)/2+scroll_ventana)
    var el=w.document.createElement('iframe');
    el.id='popUpIframe';
    el.src=direccion;
    el.scrolling='no';
    el.frameBorder=0;
    el.style.width=ancho+'px';
    el.style.height=alto+'px';
    el.style.top=pos_y.toString()+'px';
    el.style.marginLeft='-'+Math.round(ancho/2).toString()+'px';
    w.document.getElementsByTagName('body')[0].appendChild(el);   
    var cerrar=w.document.createElement('img');
    cerrar.src='/images/comunes/cerrar.png';
    $(cerrar).addClass('png');
    cerrar.onclick=function(){
    	try{	
    		w.$('popUpIframe').remove();
    		w.$('cerrar_popUpIframe').remove();
        w.$('fondo_popup').remove();    
    	}catch(ex){}
    	mostrarFlash(w);
    }
    cerrar.id='cerrar_popUpIframe';
   // cerrar.style.marginLeft='-'+Math.round(ancho/2+14).toString()+'px';
    cerrar.style.marginRight='-'+Math.round(ancho/2 - 8).toString()+'px';
    //cerrar.style.top=(pos_y-12).toString()+'px'; 
    cerrar.style.top=(pos_y + 5).toString()+'px'; 
    w.document.getElementsByTagName('body')[0].appendChild(cerrar);
    window.onscroll=function(){
			if (el)	el.style.top=Math.round((alto_ventana-alto)/2+window.getScrollTop()).toString()+'px';
			if (cerrar)	cerrar.style.top=Math.round((alto_ventana-alto)/2+window.getScrollTop()+5).toString()+'px';
		}
	}else{
		var cadena='';
		if(ancho || alto) cadena+='toolbar=0';
		if(ancho) cadena+=', width='+ancho;
		if(alto) cadena+=', height='+alto;
		ventana=window.open(direccion,'',cadena);
    ventana.focus();
	}
}

/*
Muestra una ventana de dialogo
ventana_dialgo(mensaje,nombre_boton1,string_funcion1,nombre_boton2,string_funcion2,...);
*/

function ventana_dialogo(msg){
		var w;
    if(window.parent){
        w=window.parent;
    }else{
        w=window;  
    }
    
		function ocultar_dialogo(){
			try{
        w.$('alerta').remove();
        w.$('fondo_alerta').remove();    
	    }catch(ex){};
	    if(window.ie6){
				$$('select').each(function(el){
					el.style.visibility='visible';
				});
	    }
	    if(!window.parent) mostrarFlash(w);
		}
		ocultarFlash(w);
    
    var num_args=arguments.length;
  
    var fondo=w.document.createElement('div');
    fondo.id='fondo_alerta';
    w.document.getElementsByTagName('body')[0].appendChild(fondo); 
    fondo.style.width=w.Window.getScrollWidth()+'px';   
    fondo.style.height=w.Window.getScrollHeight()+'px';   
    var div_alerta=$(w.document.createElement('div')); //new Element('div');
    div_alerta.id='alerta';
    w.document.getElementsByTagName('body')[0].appendChild(div_alerta); 
    div_alerta.innerHTML='<div>'+msg+'</div>';    
    
    for(var i=1;i<num_args;i+=2){	
        boton=$(w.document.createElement('button'));  //new Element('button');
        boton.setHTML(arguments[i]);
        boton.addEvent('click',arguments[i+1]);
        boton.addEvent('click',function(){
            ocultar_dialogo();
            w.document.onkeypress=null;
        });
        div_alerta.adopt(boton);
    }
        
    div_alerta.style.marginTop="-"+Math.round($(div_alerta).offsetHeight/2)+"px";
    w.document.onkeypress=function(){
    	ocultar_dialogo();
      w.document.onkeypress=null;
      return false;
    }
    if(window.ie6){
	  	$$('select').each(function(el){
				el.style.visibility='hidden';
			});  
    }
}

function alerta(msg){
    //alert(msg);      
    ventana_dialogo(msg,"Aceptar",function(){});
}

function confirmar(msg,funcion_si,funcion_no){
		if(!funcion_no) funcion_no=function(){};
    ventana_dialogo(msg,"Sí",funcion_si,"No",funcion_no);
}

function ocultarFlash(w){
		if(!w) w=window;
		w.$$('object','embed').each(function(el){
			var wmode=el.getAttribute('wmode');
			if(wmode) wmode=wmode.toLowerCase();		
			if(wmode!='transparent' && wmode!='opaque'){
				el.style.visibility='hidden';
			}
		}); 
}

function mostrarFlash(w){
		if(!w) w=window;
		w.$$('object','embed').each(function(el){
			el.style.visibility='visible';
		}); 
}

function cancelarRespuesta(evt){
    try{
        evt.preventDefault();
    }catch(ex){
        window.event.returnValue=false;
    }  
}

function redimensionarIframe(id){
    window.addEvent("load",function(){
    		var altura=window.getScrollHeight();
    		if(altura<300) altura=300;
        window.parent.$(id).style.height=altura+2+"px";
    });
}


function esAncestro(padre,hijo){
    try{
        if(hijo==padre)
            return true;
        if(hijo.tagName=="BODY")
            return false;
        return esAncestro(padre,hijo.parentNode);
    }catch(ex){
        return false;  
    }
}


function colorearTablas(){
    tablas=$$('table');
    for(var k=0;k<tablas.length;k++){
        trs=tablas[k].getElementsByTagName('tr');
        if(!tablas[k].hasClass('no_resaltar')){
            for(var q=0;q<trs.length;q++){
            
                if( (q%2)==0){
                    $(trs[q]).addClass('fila_color');  
                    $(trs[q]).removeClass('fila_sin_color');
                }else{
                    $(trs[q]).addClass('fila_sin_color');
                    $(trs[q]).removeClass('fila_color');
                }
                $(trs[q]).addEvent('mouseover',function(){
                    this.addClass('fila_resaltada');
                });                 

                $(trs[q]).addEvent('mouseout',function(){
                    this.removeClass('fila_resaltada');  
                });
            }
        }
    }
}

function resaltarCampo(campo){
    campo.addClass('campo_resaltado');
    campo.addEvent('keypress',function(){
        this.removeClass('campo_resaltado');  
    });
    campo.addEvent('blur',function(){
        this.removeClass('campo_resaltado');  
    });
    campo.focus();
}

function textoPorDefecto(){
    $$('.texto_por_defecto').each(function(el){
        if(el.value=='' && el.title!=''){
            el.value=el.title;
            el.addEvent('focus',function(){
                if(this.value==this.title) this.value='';
            });
            el.addEvent('blur',function(){
                if(this.value=='') this.value=this.title;
            });
        }
    });
    
     $$('form').each(function(el){
        el.addEvent('submit',function(em){
            $$('.texto_por_defecto').each(function(em){
                if(em.value==em.title) em.value='';
            });  
        }); 
     });   
}

function fechaMayor ( fechaIni, fechaFin )
{
    partes1 = fechaIni.split('/');
    fechaIniFormateada = Date.parse(''+partes1[1]+'/'+partes1[0]+'/'+partes1[2]+'');
    partes2 = fechaFin.split('/');
    fechaFinFormateada = Date.parse(''+partes2[1]+'/'+partes2[0]+'/'+partes2[2]+'');
    if (fechaIniFormateada < fechaFinFormateada ) return 2;
    if (fechaIniFormateada == fechaFinFormateada ) return 0;
    if (fechaIniFormateada > fechaFinFormateada ) return 1;
}


function contenidoIframe(ref){
//	return (ref.contentWindow.document || ref.contentDocument); 
	try{
	    return ref.contentDocument;
	}catch(ex){
	    try{
	        return ref.contentWindow.document;
	    }catch(ex2){}
	}
}

function menuHover(idMenu){
	$$('#'+idMenu+' a img').each(function(el){
		if(el.src.substr(-7,3)=='_on') return;
		el.img_off=new Image();
		el.img_off.src=el.src;
		el.img_on=new Image();
		el.img_on.src=el.src.replace(/(.*)(\.gif|\.jpg|\.png)/,"$1_on$2");
		el.addEvent('mouseover',function(){
			this.src=this.img_on.src;
		});
		el.addEvent('mouseout',function(){
			this.src=this.img_off.src;
		});		
	});
}

function mostrarFotoVar(url) {
	$('contenedor').setStyle('background-image','url('+url+')');
}

function sustituirImagen(selector,fuente,tamanyo,color,fondo,hover,sombra,offsetX){
	$$(selector).each(function(el){	
		var dimensiones=el.getSize().size;
		if(dimensiones.x==0 || dimensiones.y==0) return;
		if(dimensiones.y<tamanyo) dimensiones.y=Math.round(tamanyo*1.05);
		var padding_horizontal=el.getStyle('padding-left').toInt()+el.getStyle('padding-right').toInt();
		var padding_vertical=el.getStyle('padding-top').toInt()+el.getStyle('padding-bottom').toInt();
		if(padding_horizontal>0) dimensiones.x-=padding_horizontal;
		if(padding_vertical>0) dimensiones.y-=padding_vertical;
		if(offsetX){
			dimensiones.x+=offsetX;
		}
		var texto=el.getText();
		if(texto=='') return;
		if (el.getStyle('text-transform')=='uppercase'){
			texto=texto.toUpperCase();
		}
		var alineado=el.getStyle('text-align').toLowerCase();
		if(!color){
			color=el.getStyle('color').replace('#','');
		}
		/*if(!fondo){
			fondo=el.getStyle('background-color').replace('#','');
		}*/
		fondo='transparent';
/*****Calcular saltos de linea****/
		var div=new Element('div');
	//	div.setStyle('visibility','hidden');
		div.setStyle('font-size',el.getStyle('font-size'));
		div.setStyle('width',dimensiones.x);
		div.setStyle('font-family',el.getStyle('font-family'));
		$E('body').adopt(div);
		div.setText(texto);
		var altura_actual;
		var altura_anterior;
		var texto_final=texto;
		var longitud_texto=texto.length;	
		//if(texto.length>40) alert('a');
		var pendiente=false;
		for (var k=longitud_texto;k>0;k--){	
			altura_anterior=div.getSize().size.y;
			div.setText(texto.substr(0,k));
			altura_actual=div.getSize().size.y;		
			if(altura_actual!=altura_anterior || pendiente){
				pendiente=true;
				if(texto.substr(k-1,1)==' '){
					pendiente=false;
					texto_final=texto_final.substring(0,k-1)+String.fromCharCode(10)+texto_final.substr(k,longitud_texto);	
					dimensiones.y+=Math.round(tamanyo/5);
				}
			}
		}
		div.remove();
		texto=texto_final;
		
/*********************************/
		
		var src='/bd/titulares/'+(texto+fuente+color+tamanyo+fondo).replace(/[^a-zA-Z0-9]/g,"")+'.png';
		
		var img=new Element('img', {
			alt:texto,
			'class':'texto_reemplazado'
		});
		
		
		el.innerHTML='';
				
		img.onerror=function(){  
			src='/imagenes/titular/'+fuente+'/'+tamanyo+'/'+dimensiones.x+'/'+dimensiones.y+'/'+fondo+'/'+color;
			if(sombra){
				src+='/'+sombra;
			}else{
				src+='/0'
			}
			src+='/'+alineado;
			src+='?texto='+encodeURI(texto);
			img.src=src;
			this.onerror=null;
			this.onmouseover=null;
			this.onmouseout=null;
		}	
		img.src=src;
		el.adopt(img);

		
		if(window.ie){
			img.onload=function(){
				var x=this.width=( parseInt(this.offsetWidth,10)-parseInt(this.getStyle('paddingLeft'),10)-parseInt(this.getStyle('paddingRight'),10) );
				var y=this.height=( parseInt(this.offsetHeight,10)-parseInt(this.getStyle('paddingTop'),10)-parseInt(this.getStyle('paddingBottom'),10) );
				if(window.ie6)img.addClass('png');
			}
		}
		
		if(hover){
			img.imageHover=new Image();
			img.onmouseover=function(){
				this.src=this.imageHover.src;
			}
			img.imageHover.onerror=function(){  
					var src_on='/imagenes/titular/'+fuente+'/'+tamanyo+'/'+dimensiones.x+'/'+dimensiones.y+'/'+fondo+'/'+hover;
					if(sombra){
						src_on+='/'+sombra;
					}
					src_on+='?texto='+encodeURI(texto);
					this.src=src_on;
					this.onerror=null;
					img.onmouseover=null;
					img.onmouseout=null;
				}	
			img.imageHover.src='/bd/titulares/'+(texto+fuente+hover+tamanyo+fondo).replace(/[^a-zA-Z0-9]/g,"")+'.png';
			
			img.onmouseout=function(){
				this.src=src;
			}
		}
	});
	
}

function crearCalendario(){
	return new DatePicker();
}


function calendario_input(){
	$$('.fecha').each(function(el){
		if(el.getTag()=='input'){
			var w;
			var iframe_contenido=false;;
			if(window.parent){
        w=window.parent;
        w.$$('iframe').each(function(iframe){	
        	if(window.document==contenidoIframe(iframe)){
        		iframe_contenido=iframe;
        	}
        });
        
	    }else{
	      w=window;  
	    }
	    var img=document.createElement('img');
			img.src='/images/intranet/ico_fecha.gif';
			img.className='img_aux';
			$(img).injectAfter(el);
			img.addEvent('click',function(){
				var offsetX=el.getLeft();
				var offsetY=el.getTop();
				if(iframe_contenido){
						offsetX+=iframe_contenido.getLeft();	
        		offsetY+=iframe_contenido.getTop();	
				}
				var obj=this;
				w.dp=w.crearCalendario();
				
				var partes_clase=el.className.split(' ');
				var longitud_partes_clase=partes_clase.length;	
				for (var k=0;k<longitud_partes_clase;k++){	
					if (partes_clase[k].substr(0,7)=='dp_ini_'){
						w.dp.fecha_ini=partes_clase[k].substr(7);	
					}
					if (partes_clase[k].substr(0,7)=='dp_fin_'){
						w.dp.fecha_fin=partes_clase[k].substr(7);
					}
				}
				
				w.fecha_elm = w.dp.create();
				w.dp.onchange=function(){
					var fecha_elegida=this.getDate();
					var mes=this.getDate().getMonth();
					var dia=this.getDate().getDate();
					var anyo=fecha_elegida.getFullYear();
					fecha_elegida=new Date(anyo,mes,dia);	
					if (fecha_elegida)  {
						if( (this.obj_fecha_ini && fecha_elegida<this.obj_fecha_ini ) || ( this.obj_fecha_fin && fecha_elegida>this.obj_fecha_fin ) ){
						}else{
							mes++;
							if (mes<10) mes='0'+mes;
							if (dia<10) dia='0'+dia;
							el.value=dia+'/'+mes+'/'+anyo;
						}

					}else{
						el.value='';
				  }
				}
				w.document.getElementsByTagName('body')[0].appendChild(w.fecha_elm);
				w.fecha_elm.style.left=offsetX+100+'px';
				w.fecha_elm.style.top=offsetY-145+'px';
				
				
				
				
			});
	    
			
		}
	});
}


function menuSeleccionado(){
	$$('#menu_arbol a').each(function(el){
		if(el.href==window.location.href){
			el.addClass('seleccionado');
			//el.innerHTML+=' &gt';
		}
	});
}

function toolTips(){
	var imgs=$$('img[title!=""],a[title!=""]');
	imgs=imgs.filter(function(el){
		return el.title!='';
	});
	if(window.ie){
		imgs.each(function(el){
		el.removeAttribute('alt');
		el.longdesc=el.title;
		});
	}
	var myTips = new Tips(imgs, {
			initialize:function(){
				this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 200, wait: false}).set(0);
			},
			onShow: function(toolTip) {
				this.fx.start(1);
			},
			onHide: function(toolTip) {
				this.fx.start(0);
			},
			showDelay: 400
    });
}

function igualarAltura(selector){
	window.addEvent('load',function(){
		var altura_maxima=0;
		var coleccion=$$(selector);
		coleccion.each(function(el){
			var altura=el.getSize().size.y-el.getStyle('padding-top').toInt()-el.getStyle('padding-bottom').toInt();
			if(altura>altura_maxima) altura_maxima=altura;
		});
		coleccion.each(function(el){
			el.setStyle('height',altura_maxima);
		});
	});
}

function encuestasVotar(){
	
	var animarBarras=function(){
		$$('.encuesta .barra div').each(function(el){
			el.addClass('con_color');
			el.effect('width', {duration:1500}).start(0,el.getSize().size.x);
		});
	}
	
	window.addEvent('domready',function(){
		$$('.encuesta form').each(function(encuesta){
			encuesta.getElements('input').each(function(el){	
				el.onclick=function(){
					encuesta.onsubmit=function(){return false;}
					encuesta.send({update:encuesta, onSuccess:animarBarras});
					return false;
				}
			}); 
		});
		
		animarBarras();
		
	});
	
}

	
function crearPuntoGoogle(point,titulo,texto,icono,ir_a_enlace) { 
	texto=texto.replace(/\n/gi,"<br />");
	var icon_green = new GIcon();
	if(icono){
		icon_green.image = icono;
			icon_green.iconSize = new GSize(24, 24);
	}else{
		icon_green.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
		icon_green.iconSize = new GSize(12, 20);
	}
	icon_green.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";

	icon_green.shadowSize = new GSize(22, 20);
	icon_green.iconAnchor = new GPoint(6, 20);
	icon_green.infoWindowAnchor = new GPoint(5, 1);
  var marker = new GMarker(point, icon_green);
  GEvent.addListener(marker, 'click', function() {
  	if(ir_a_enlace){
  		window.location.href=ir_a_enlace;
  	}else{
	  	if($('NombreTextoEs')){	
				titulo=$('NombreTextoEs').value;	
			}
			if($('SubtituloTextoEs')){
				texto=$('SubtituloTextoEs').value.replace(/\n/gi,"<br />");
			}	
	  	var etiqueta='<strong>'+titulo+'</strong><p>'+texto+'</p>';
			marker.openInfoWindowHtml(etiqueta);
		}
  });
  return marker;
}

function mapaInicializar(id_mapa,longitud,latitud,zoom,tipo){
	var mapa = new GMap(document.getElementById(id_mapa));
	mapa.addMapType(G_PHYSICAL_MAP);
	mapa.addControl(new GSmallZoomControl3D());
	mapa.addControl(new GMenuMapTypeControl());
	var latlng=new GLatLng(latitud,longitud);
	mapa.setCenter(latlng,Number(zoom));
	for(k=0;k<G_DEFAULT_MAP_TYPES.length;k++){
  	if(G_DEFAULT_MAP_TYPES[k].getName()==tipo){
  		mapa.setMapType(G_DEFAULT_MAP_TYPES[k]);
  	}
	}
	if(G_PHYSICAL_MAP.getName()==tipo){
		mapa.setMapType(G_PHYSICAL_MAP);
	}
	return mapa;
}

function mapaGoogleMultiple(id_mapa,longitud,latitud,zoom,tipo,puntos,ir_a_enlace){
	mapa=mapaInicializar(id_mapa,longitud,latitud,zoom,tipo);
	for(var k=0;k<puntos.length;k++){
		marker=crearPuntoGoogle(new GPoint(puntos[k].longitud,puntos[k].latitud),puntos[k].titulo,puntos[k].texto,puntos[k].icono,puntos[k].ir_a_enlace);
  	mapa.addOverlay(marker);
	}
}

function mapaPosicion(id_mapa,longitud,latitud,zoom,tipo,titulo,texto,icono){
	mapa=mapaInicializar(id_mapa,longitud,latitud,zoom,tipo);
	/*var mapa = new GMap(document.getElementById(id_mapa));
	mapa.addControl(new GLargeMapControl());
	mapa.addControl(new GMapTypeControl());
	var latlng=new GLatLng(latitud,longitud);
	mapa.setCenter(latlng,Number(zoom));*/
	marker=crearPuntoGoogle(new GPoint(longitud,latitud),titulo,texto,icono);
  mapa.addOverlay(marker);

  /*
  for(k=0;k<G_DEFAULT_MAP_TYPES.length;k++){
  	if(G_DEFAULT_MAP_TYPES[k].getName()==tipo){
  		mapa.setMapType(G_DEFAULT_MAP_TYPES[k]);
  	}
  }*/
  return mapa;
}


window.addEvent('domready',textoPorDefecto);
window.addEvent('domready',calendario_input);
window.addEvent('domready',toolTips);
