$(document).ready( function()
{



/*BOOK:NOTICIA. A CONTINUACION , TODO LO RELATIVO A ABRIR Y CERRR LAS PERSINANAS DE LAS NOTICIAS DE LA HOMe*/
	/* mas adelante esta lo relativo a sus posiciones y recalculo de las mismas en resize */

// de entrada las noticias-video se abren solitas sin interaccion humana

//si las dimensiones de la pantalla son menores de xxx hcer que las noticias video tambien se queden ocultas. Para eso le quitamos la clase de noticia-siempre-abierta
// TO_DO:  hacer esta misma comprobacion a cada resize

// si la noticia tiene la clase "noticia-siempre-abierta", entonces se abre automaticamente al empezar la pagina.


	if ($(window).height() < 600)
			$('.noticia-siempre-abierta').removeClass('noticia-siempre-abierta').addClass('noticia-siempre-abierta-ahora-cerrada');
    setTimeout(
		function() { $('.noticia-siempre-abierta').children().children('.contenido-oculto').show("slow"); }
		, 1500
		);

	var mouseOverNoticia = false;  //flag, dice si estamos sobre una noticia o no, para q no haga cosas raras
	var idNoticia = ""; //dice el id de la +ultima noticia sobre la q se hizo rollover

	$('.noticia').not('.noticia-siempre-abierta').mouseover(function(){
		mouseOverNoticia  = true;
		idNoticia = $(this).attr('id');
		if (mouseOverNoticia) abreNoticia();
	});
	$('.noticia').not('.noticia-siempre-abierta, .noticia-siempre-abierta-ahora-cerrada').mouseout(function(){
		mouseOverNoticia  = false;
		setTimeout(function(){
		if (!mouseOverNoticia) cierraNoticia();
		}, 200);
	}); /*TO_DO: meter el efecto de drag en click y que deje de drag en mouseUp*/

	function abreNoticia()
	{	
		$(".noticia").not('.noticia-siempre-abierta').each(function(){ 
			if ($(this).attr("id") != idNoticia)
			{
				$(this).children().children('.contenido-oculto').hide("slow");
			}else $(this).children().children('.contenido-oculto').slideDown('slow');
		});
//		$(".noticia").not('#'+idNoticia).children().children('.contenido-oculto').hide("slow", function(){ alert(idNoticia); $('#'+idNoticia).children().children('.contenido-oculto').slideDown('slow');} ) ;	
	}
	function cierraNoticia() // TO_DO: que cierre noticia solo si estaba abierta y viceversa
	{ 	$('#'+idNoticia).children().children('.contenido-oculto').slideUp('slow');		}


	/*-------------------------------*/
/*FIN DE TODO LO RELATIVO A ABRIR Y CERRR LAS PERSINANAS DE LAS NOTICIAS DE LA HOMe*/





	/*  BOTONES DE DERECHA E IZQUIERDA PARA LOS PROYECTOS EN CLOSE UP  */


	var mouseSobreBoton = "";
	var speedDesliza = "90";
	var tiraIconos = $('#closeupproyectos ul');
	var ultimoItemTira = $('#closeupproyectos ul li:last');
	var maxOffsetLeft = tiraIconos.offset().left;
	var offSetInicial = 180; 

	comprobarEstadoFlechas();

	function comprobarEstadoFlechas()
	{
		var tiraIconos = $('#closeupproyectos ul');
		var ultimoItemTira = $('#closeupproyectos ul li:last');
		var maxOffsetLeft = tiraIconos.offset().left;


	 // verifica si la lista de opere puede ser movida mas aun en una direcion. Si no es asi, se oculta la flecha
	 var extremoIzqTira = (ultimoItemTira.offset().left) + (ultimoItemTira.width());
		if ( extremoIzqTira <= $(window).width()-280 )
			$('#boton-desliza-dcha a').hide();
		else if (!$('#boton-desliza-dcha a').is(':visible')) 	$('#boton-desliza-dcha a').show();

		if ( tiraIconos.offset().left >= offSetInicial )
			$('#boton-desliza-izq a').hide();
		else if (!$('#boton-desliza-izq a').is(':visible')) 	$('#boton-desliza-izq a').show();

//		alert(" final tira: "+ extremoIzqTira +" - width pag "+$(window).width()+" - 280 . Left tira ic : "+tiraIconos.offset().left+" . Max offset left "+maxOffsetLeft);
   }
	$(window).resize(function(){
		comprobarEstadoFlechas();
		}	);

	$('#boton-desliza-dcha a').click(function(){
		mouseSobreBoton = "dcha";

		if (  ultimoItemTira.offset().left + ultimoItemTira.width() > $(window).width()-280 )
		{
			tiraIconos.animate(
				{ marginLeft: '-='+speedDesliza+'px' }	,
				100,
				function(){ if (mouseSobreBoton == 'aquivendriadcha') $(this).mouseover(); /*else $(this).stop();*/  comprobarEstadoFlechas();}
				);	
		}
		
	})
	$('#boton-desliza-izq a').click(function(){
		mouseSobreBoton = "izq";

		if ( tiraIconos.offset().left < maxOffsetLeft )
		{

			$('#closeupproyectos ul').animate(
					{ marginLeft: '+='+speedDesliza+'px' }	,
					100,
					function(){ if (mouseSobreBoton == 'aquivendriaizq') $(this).mouseover(); /*else $(this).stop();*/ comprobarEstadoFlechas(); }
			);	
		}
		
	})

	$('.boton-desliza').mouseout(function(){ 
				mouseSobreBoton = ""; /*bandera para saber si seugmos aplicando el efecto*/
			//	$(this).stop();				
			}).click(function(){ return (false);} );
	/*FI DE TODO LO RELATIVO A LA TIRA DE PROGECTOS EN CLOSEUP DE LA CABECERA*/





	/*efecto común de HOVE, substituye la imagenpor la misma pero con nombre imagen_over.gif (TO_DO: solo contempla el caso de imagen .gif, se podría hacer universal) */
	/*aplicable a la imagen o al <a> q la contiene*/
	/*BOOK:HOVER-JS*/
	$('.hover-effect').hover(function() { 
			var img = $(this).children('img:first');
			if (img.attr("src") === undefined)	img = $(this); 
//			var src = img.attr("src").replace(/\\/g,'/').replace( /.*\//, ''); //basename()
//			var dir = img.attr("src").replace(/\\/g,'/').replace(/\/[^\/]*$/, ''); //dirname()
			var src = img.attr("src").replace( ".gif" , "_over.gif").replace(".jpg", "_over.jpg").replace(".png", "_over.png"); //esto devuelve el basename()
            img.attr("src", src);
        },
           function() {
			var img = $(this).children('img').eq(0);
			if (img.attr("src") === undefined)	img = $(this); 
            var src = img.attr("src").replace("_over", "");
           img.attr("src", src);
        });

	/*fin efecto hover*/

	/*efecto centelleo- para algunos links*/
	$('.efecto-centelleo').mouseover(function(){
		$(this).animate({ opacity: 0.5 }, "fast" , function (){ $(this).animate( { opacity: 1 },"slow" ); }    );
	});

}); // ready 
/*...................................................................................................................................*/
	


	function escalarImagenFondo()
	{
		$(".div-fondo-home").css({ height: $(window).height() });

	
		//y aqui acabamos, no evaluamos de que sea demasiado alto respecto a la anchura
	}


	function initHomepage(listaSrc, numImagen)
	{
	/*En esta funcion ponemos en orden todo lo relativo a la home*/


		//reescalamos la imagen de la home del tamanho de la window menos el menu
		escalarImagenFondo();
	
		
		// VAMOS A CARGAR LA IMAGEN DE ALTA CALIDAD
		srcImagen = listaSrc[numImagen].hi;

		var str = '<img alt="" src="'+srcImagen+'" />';

		$('#div-fondo-nitido').append(str);

		setTimeout( function(){
			$('#div-fondo-nitido').fadeIn(5000);
		}, 5000);

		setTimeout( function(){
			//actualizacionImgFondo(listaSrc, numImagen)
		}			
		);



		/*BOOK:NOTICIA. */

			/*CREACION D UN ARRAY QUE ME SALVA LAS COORDENADAS DE CADA NOTICIA CADA VEZ QUE LA DESPLAZO*/
			function coordenadas(idElemento, posX, posY) // Creamos una nueva clase
				{				
					this.id = idElemento; 
					this.posX = posX;
					this.posY = posY;
				}		
			var coordenadasNoticias = [new coordenadas('div-fondo-borroso', $(window).width(), $(window).height())]; //init del array
													 //  ^indiferente el elemento en este caso pero=>coordenadasNoticias[0].posX;  -->salva las dimensiones de la pantalla

			function actualizaCoordenadas(idElemento, posX, posY) //estaria bien como crear esta fcion como metodo de la clase "coordenadas"
				{
						for(i=0; i<coordenadasNoticias.length; i++) 
							if (idElemento == coordenadasNoticias[i].id)
						{
							coordenadasNoticias[i].posX = posX;
							coordenadasNoticias[i].posY = posY;
						}
				}
			//fin delas funciones de apoyo, comienza la marcha

			jQuery.each($('.noticia'), function(i, val) {				
							coordenadasNoticias.push(new coordenadas($(val).attr('id'), $(val).offset().left, $(val).offset().top) );
					  });


	/*   EFECTO DE ARRASTRAR LAS NOTICIAS CON EASYDRAG.  esa libreria de jquery ocupa solo 4 k!!!!*/
	/*tiene la ventaja de q ocupa muy poco y de que aparece ya el cursor de arrastras, y permite seleccionar texto y arrastrar la noticia desde cualquier punto que se clique
	Hacef lat inicializar jquery_dragndrop.js en header
	 */
			$(".noticia").not('.no-draggable').easydrag();
			$(".noticia").ondrop(function(e, element){ 
							// CUANDO SE POSICIONE EL ELEMENTO SE PODRIA CALCULAR SU DISTANCIA Y TAL...
							// al posarlo guardamos sus coordenadas, q se usaran por si se redimensiona la pantalla, pder interpolar las posiciones
						actualizaCoordenadas($(element).attr('id'), $(element).offset().left, $(element).offset().top);
					});
	/*   .-----------------------..... */


		
		/* efecto de arrastre de noticia con jquery ui. Tiene la ventaja de que restringe el espacio de arrastre a las proporciones del padre.
			Permite que se pueda arrastrar solo desde el cuadrado si se quiere.. No pone el cursor de arrastre, pero es facil de imitar.
			HACE FALTA INICIALIZAR EL jquery-ui-1.7.2.custom.min.js (pesa 40 K)
		*/
		//	$(".noticia").draggable({ containment: '#div-fondo-borroso', scroll: false, handle: '.cuadrado'});

			/*para redistribuir las noticias */
			$(window).resize(function(){
				  //alert("Stop it!"); // funciona:  aplicar la recolocacion de las imagenes
				 // interpolacion entre posiciones antiguas y nuevas, respecto a tamano de div-fondo-borroso anterior y actual

					//reescalamos la imagen de la home del tamanho de la window menos el menu
				//$(".div-fondo-home").css({ height: $(window).height() - $("#header").height() - $("#menu").height() + 3 });//parece q funciona, pero no está muy testado
				
				



				escalarImagenFondo();

				widhPantalla_original = coordenadasNoticias[0].posX;
				heightPantalla_original = coordenadasNoticias[0].posY;
				// alert("entro en resize: with anterior "+widhPantalla_original +", ahora es : "+$(window).width());
				if (widhPantalla_original != $(window).width())	 //curiosamente esto evita q en chroe la not1 pille la posY de noticia 3			
				jQuery.each($('.noticia'), function(i, val) { //i es el indice del each. coordenadasNoticias[i+1] corresponde a las pos de noticia-i+1

					leftNoticia_original = coordenadasNoticias[i+1].posX;
					topNoticia_original = coordenadasNoticias[i+1].posY;
					
					leftNoticia_definitivo = ((leftNoticia_original * $(window).width()) / widhPantalla_original);
					topNoticia_definitivo = ((topNoticia_original * $(window).height()) / heightPantalla_original);

				//	alert(  "POS NTICIA: "+i+" /n OriginaL: "+leftNoticia_original+" - "+topNoticia_original+" \n defit: "+leftNoticia_definitivo+" - "+topNoticia_definitivo+" ");
					// ASIGNAR NUEVA POSICION

					// TO_DO:
					// esto admite mucha mas validacion: evitar que la noticia se vaya por la derecha, que se sobreponga al menu
					// que quede muy cerca del bottom y al desplegarse no vaya bien ...
					// tambien admite que se recalculen sus boundaries de area draggable aceptable
					
					//validacion de que la nueva pos no se pase por la derecha ni por abajo
					if (leftNoticia_definitivo > $(window).width() - $(this).width())
						leftNoticia_definitivo = $(window).width() - $(this).width();




					$(val).animate({ left:leftNoticia_definitivo+"px", top:topNoticia_definitivo+"px" }	);					
					//css(					{ left:leftNoticia_definitivo+"px", top:topNoticia_definitivo+"px" }				);  
					actualizaCoordenadas($(val).attr('id'),leftNoticia_definitivo, topNoticia_definitivo);
					actualizaCoordenadas('div-fondo-borroso', $(window).width(), $(window).height());
					}); //Jquery foreach
			
				}); // resize
			/*fin para redistribuir las noticias */
		/*fin de los efectos para las notiias flotantes*/


	} //fin initHomepage



	
  /* TODO SLIDESHOW PARA PASAR IMAGENES DE UNA A OTRA CON FADES*/

  // primero, al cargar la pagina cargamos el slideshow. Lo hacemos asi pq los parametros de los nombres de imagenes estan generados en php
  // en el html, en la imagen-pagina hay un onclick que llama a cargarSlideShow

  $("#imagen-pagina").click();


	var delay = 6000;
	var indiceImg = 0;
	var play = true;
	var numImagenes = ""; //inicializar con la funcion
	var enTransicion = false;
	var id_imagen = ""; //incializar en la fcion

  function cargarSlideShow(arr, id_imagen_pasada)
	{

	// funcion interesante para crear slide show. Tan solo necesite una estructura de tipo <div><img id="myim" src="imgdefecto.jpg"></div>
	// se pasa un array con los src que ira rolando, y la id "myim".
	// la funcion crea otra imagen invisible y entre las dos va intercambiando de imagen.
	
	id_imagen = id_imagen_pasada;

	// 1. creamos la otra imagen invisible sobre la que rodamos e intercambaimos la lista
	for (i=1 ; i<arr.length ; i++ ) //no cargamos la primera imagen pq interpretamos q es la que ya está puesta
	{
		var nuevaImgHTML = "<img id='"+id_imagen+(i)+"' src='"+arr[i]+"' class='nodisplay' />";
		$('#'+id_imagen).parent().append(nuevaImgHTML);
	}

	
	numImagenes = $('#'+id_imagen).parent().children().length;

	
	if (numImagenes > 1)
		setTimeout(function(){playGaleria(1);}, delay/2 ); //poner delay/2 para q este bien


	 } // cargarSlideShow


	function playGaleria(indiceImagenActualizada)
	{


		var id = id_imagen+(indiceImg);
	 	if (indiceImg == 0) id = id_imagen;


		if (indiceImagenActualizada >= numImagenes ) indiceImagenActualizada = 0;

		if (indiceImagenActualizada == 0) id_actualizada = id_imagen;
		else id_actualizada = id_imagen+(indiceImagenActualizada);


		//INTERCABIO DE IMAGENES,CON CALLBACKS

		//antes de desaparecer, ponermos la imagen como fondo del contenedor padre, para que quede de fondo y sea mas guay
		$('#'+id).parent().css({
			backgroundImage: "url('"+$('#'+id_actualizada).attr('src')+"')",
			backgroundRepeat: "no-repeat"
		});
		// OJO: si las imagenes no son del mismo tamanho esto queda un poco mal


		// INTERCAMBIO:::: 
		$('#'+id).fadeOut("slow", function(){ $('#'+id_actualizada).fadeIn("slow"); });

		// actualizacion de indiceImg;
		indiceImg = indiceImagenActualizada;

		
		// continuacion del slideshow
		var sigImg = indiceImg + 1;
		if (sigImg >= numImagenes ) sigImg = 0;
		if (play) setTimeout(  function(){  playGaleria(sigImg); }, delay);
	
	} //fi  funcion playGaleria














		function getFlashObj(movie){
		   if (window.document[movie]) {
			  return window.document[movie];
		   }
		   if (navigator.appName.indexOf("Microsoft Internet")==-1) {
			  if (document.embeds && document.embeds[movie]) {
				 return document.embeds[movie]; 
			  }
		   } else {
			  return document.getElementById(movie);
		   }
		}
		function getDimensions(movie) {

		  // var movieObj = getFlashObj(movie);
		
//		   var width = movieObj.TGetProperty("/", 8); //esto no va
//var height= movieObj.TGetProperty("/", 9);
//		   alert("The current dimensions for the Flash Object ("+movie+") are "+width+" in width and "+height+" in height.");
		}




	// funcion practica para pasar variables de php para q use js en cualquier momento. El php crea codigo escondido en html, que se guarda con separadores del tipo  llave1==valor1***llave2==valor2***llave3==valor3
	// y se pasa este html al js, que con un esteHTML.split("***") identifica las duplas, y ocn esta funcion recoge el valor asociado a una key
	//no olvidar que son dos "=" y no uno.
	function get_key(dupla)
	{
		if (dupla.indexOf('==') > 0)
			return dupla.substring(0, dupla.indexOf('=='));
	}
	function get_valor(dupla)
	{
		if (dupla.indexOf('==') > 0)
		return dupla.substring(dupla.indexOf('==')+2);
	}
	
	
	
	function initProgetto()
	{
	
		// TODOE EL JS dedicado a la pagina de single cuando el objeto es una "opere"

		$('.demo-popup').click(function(){

				// se crea:     #demo-abosulte  --> contenedor oscuro con transparencia q ocupa todo. Sus dims se calculan dinámicamente
				//					#demo-absolute-titulo-y-embed
				//							#demo-titulo
				//							object #demo-movie

			$('#demo-absolute').remove();  //  demo absolute es un div que se crea en tiempo real con js para meter el objeto embebido
			var html = '<div id="demo-absolute" class="ventana-velada" >';

			dataDemo = $(this).children("code").html(); //el tag code (dentro del boton de la Demo ) nos dice el titul
			dataDemoArray = dataDemo.split("*|*");
			//alert(typeof(dataDemoArray));
			guid=""; width="100%"; height= "100%" ;   

			for ( var i in dataDemoArray )  // evaluamos todas las variables pasadas desde la tag "code" y las guardamos
			{
				if (get_key(dataDemoArray[i])=='post_title') 
					titulo =  get_valor(dataDemoArray[i]); //alert (titulo);
				if (get_key(dataDemoArray[i])=='guid') 
					guid = get_valor(dataDemoArray[i]); //alert (guid);
				if (get_key(dataDemoArray[i])=='width') 
					width = get_valor(dataDemoArray[i]); //alert (width);  //el width y el height vienen y desde code con la extension .px  
				if (get_key(dataDemoArray[i])=='height') 
					height = get_valor(dataDemoArray[i]); //alert (height);
				if (get_key(dataDemoArray[i])=='post_content') 
					desc = get_valor(dataDemoArray[i]); //alert (height);
					
			}

				/*TO_DO: capturar las dimensiones del mov o flash, y ponerlo en el embed  http://blog.codefidelity.com/?p=14*/
				/*TO_DO: pasar a minusculas el codigo del embed*/
				/*TO_DO: evaluar el caso de que sea flash , shockwave, o imagen*/


			html += "<div id='demo-absolute-titulo-y-embed'>";
			html += "<div id='demo-titulo'> "+titulo+" - demo ";
			html += "  <div id='demo-boton-cerrar'> <a href='#' onclick='$(\"#demo-absolute\").fadeOut(\"slow\", $(\"#demo-absolute\").remove());'><img class='floatleft;' alt='chiudere/close' src='http://mandu.mitreum.net/wp-content/themes/altair4/images/close.png'/></a></div>";
			html += "</div>";
			html += "<div id='demo-desc'> "+desc+"</div>";
			html += '  			<object id="demo-movie" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" ';
			html += '  						style="width:'+width+'px; height:'+height+'px;" codebase="http://www.apple.com/qtactivex/qtplugin.cab">';
			html += '  						<param name="src" value="'+guid+'">';

			html += '  						<param  name="autoplay" value="true">';
			html += '  						<param  name="controller" value="true">';
			html += '  						<embed src="'+guid+'" autoplay="true"';
			html += '  						controller="true" width="'+width+'" height="'+height+'"';
			html += '  						pluginspage="http://www.apple.com/quicktime/download/">';
			html += '  						</embed>';
			html += '  			</object>';

			
			html += "</div>";
			html += "</div>";



			$('body').append(html);

			w = $('#demo-movie').width();
			h = $('#demo-movie').height();
			//alert(w+" x "+h);



			return (false);		
		});

		
	
	} //fin initProgetto




	//botno para hacer la persiana desplegable de la pagina de elenco
		//id post parent es por si  usamos ajax, para llamarlo con el id adecuado
	function abrirSublista(idSublista, idPostParent)
	{

	  $('.lista-subelementos:visible').slideUp().removeClass('sublista-activa'); 	  
	  $('#'+idSublista).show('slow').addClass('sublista-activa'); 
	  
	  $('.boton-mostrar-sublista').show();
	  $('#boton-mostrar-sublista-'+idSublista).hide();
	  
	  return (false);
	}


	function loadjsfile(filename){
	
		  var fileref=document.createElement('script')
		  fileref.setAttribute("type","text/javascript")
		  fileref.setAttribute("src", filename)
		  if (typeof fileref!="undefined")
		  document.getElementsByTagName("head")[0].appendChild(fileref);

	}

