var margen_arriba = 24;
var margen_lados = 37;
var anchoBloques = 230 + 10;
var arrOrden;	
var arrHeight;	
var arrPosicionInicial;
var anchoMinimo = 554;

var speedPlegarBloques = 300;
var speedDesplegarBloques = 300;
var speedIrNoticia = 500;
var speedVolverNoticia = 500;
var speedAbrirSubElemento = 300;
var speedCerrarSubElemento = 300;
var speedColocarBloques = 500;
var speedRedimensionarbloques = 200;
var speedColocarLogoNeo = 500;
var speedAbrirFull = 300;
var speedCerrarFull = 200;
var speedCarruselSede = 600;

var topCerrarFull = 0;
var leftCerrarFull = 0;
var topCerrarFullSede = 0;
var leftCerrarFullSede = 0;

$(document).ready(function($){
	ordenaBloques(true, true, true);
	ordenaBloquesInicio(1);
	

	$(window).resize(function() {
		ordenaBloques(true, true, false);
	});

//	cargaListadoNoticias();
	addListenerClickVinculosListadoNoticias();

	$("a.volver-noticia").click(function(){
		$('.contenedor-noticias').animate({left: -0}, speedVolverNoticia, function() {
			$('.detalle-noticias .jspPane').html('');
/* ----------------------- */
/* INICIO altoBloque() --> */
/* ----------------------- */
				altoBloque($('.desplegado'), false);
/*
			arrHeight[bloqueDesplegado.attr('class').substr(7) + 1]= alto;
			altoMaximo=$('.desplegado').offset().top  + $('.desplegado').parent().height() - 101 ;
			bloqueDesplegado=$('.desplegado').parent();
			if (bajoLogo(bloqueDesplegado)) {
				altoMaximo = altoMaximo - $('#div_logo_neo').height() + 10;
			}
			alto = arrHeight[bloqueDesplegado.attr('class').substr(7)];
	
$('#alto-bloque-desplegado').html(alto + ' - ' + altoMaximo);
			if (alto > altoMaximo) alto = altoMaximo;
	
			bloqueDesplegado.children('.contenido_bloque').stop(true).animate({'height': alto}, speedRedimensionarbloques, function() {
	
				if (!bloqueDesplegado.children('.contenido_bloque').hasClass('noticias')) {
	// 								bloqueDesplegado.children('.contenido_bloque').css('overflow', 'auto');
				}
				$('.contenedor-noticias').css({'height': alto});
				$('.listado-noticias').css('height', alto - 3);
				$('#div_detalle_noticia').css('height', alto);
			})
*/
/* ----------------------- */
/* <-- FIN altoBloque()    */
/* ----------------------- */
		})
		$('.volver-noticia').fadeOut('slow');
		
		return false;
//		cargaListadoNoticias(true);
	});

	$("a.link-bloque").click(function(){
		

		if ($(this).parent().children('.contenido_bloque').hasClass('sede')) {
			//es sede, abrimos la opción correspondiente
			topCerrarFullSede=$(this).offset().top + ($(this).height() / 2);
			leftCerrarFullSede=$(this).offset().left + ($(this).width() / 2);
			$('#div_sede_full').css({
				'z-index': '99',
				'top': topCerrarFullSede,
				'left': leftCerrarFullSede
			});
			$('#div_sede_full').stop(true).animate({
				'width': 'toggle',
				'width': 'toggle',
				'top': '24',
				'left': '37'
			}, speedAbrirFull, 'easeOutBack', function(){})
			return false;
		}
		
		
		
		var vinculo = $(this);
		var bloque=vinculo.parent();
//alert(bloque.attr('class'));		
//		$(".contenido_bloque:visible").slideUp("slow");
		if (vinculo.hasClass('desplegado')) {
//alert('pliega el abierto')
			plegarBloque(bloque, "");
		} else {
			//antes de desplegar, revisamos si hay otro desplegado.
			if ($('a[class~=desplegado]').length>0) {
				bloqueDesplegado=$('a[class~=desplegado]').parent();
//alert('está abierto el ' + bloqueDesplegado.attr('class') + ', lo cierra y luego abre el pulsado, que es el ' + bloque.attr('class'))
				plegarBloque(bloqueDesplegado, bloque);
//			} else {
//alert('no hay ninguno abierto, abre el pulsado')
//				desPlegarBloque(bloque);
			}
//			desPlegarBloque(bloque);
			
/* *********************************** */
/* desplegar --> */
//			bloque.children('.contenido_bloque').slideDown(300);


	vinculo=bloque.children('a.link-bloque');
/*
	var finalBloque;
	if (bloque.children('.contenido_bloque').hasClass('2bloques')&&bloque.attr('class')!=$('#div_contenido > div[class^=bloque_]:last-child').attr('class')) {
		finalBloque =	bloque.offset().left + 470;
	} else {
		finalBloque =	bloque.offset().left + bloque.width();
	}
	var anchoVentana  = $(window).width();
	var anchoLogo = $('#div_logo_neo').width() + 37;
	bajoLogo = finalBloque > anchoVentana - anchoLogo
 */


			$(this).addClass('desplegado');
			//si el bloque es doble, ampliamos el ancho del botón
			if (bloque.children('.contenido_bloque').hasClass('2bloques')) {
				$(this).addClass('bloquedoble');
				
				
				//si es el último lo desplazamos a la izquierda
				if (bloque.attr('class')==$('#div_contenido > div[class^=bloque_]:last-child').attr('class')) {
					posLeft=bloque.offset().left;
					posLeft=posLeft - 240
	 				bloque.css('left', posLeft);
				}
				//si es el bloque de contacto, usamos z-index para que contacto esté por encima de noticias.
			}
			bloque.css('z-index', '90');
			bloque.next().css('z-index', '0');					


/* ----------------------- */
/* INICIO altoBloque() --> */
/* ----------------------- */
						altoBloque(vinculo, true);
/*

			altoMaximo=bloque.offset().top - 70;
			if (bajoLogo(bloque)) {
				altoMaximo = altoMaximo - $('#div_logo_neo').height()  + 10;
			}

			indiceBloque = bloque.attr('class').substr(7);
			alto = arrHeight[indiceBloque];
				
			if (alto > altoMaximo) alto = altoMaximo;
			
			bloque.children('.contenido_bloque').stop(true).css({'height': alto});
			bloque.children('.contenido_bloque').stop(true).animate({'height': 'toggle'}, speedDesplegarBloques, 'easeOutBack', function() {
				if (!bloque.children('.contenido_bloque').hasClass('noticias')) {
				//bloque.children('.contenido_bloque').css('overflow', 'auto');
				}
			});

			mueveElementosPorEncima(bloque, true)

$('#posicion-logo').html('NO noticias');

			if (bloque.children('.contenido_bloque').hasClass('noticias')) {
				$('.contenedor-noticias').css({'height': alto - 0, 'top': 0});
				$('.listado-noticias').css('height', alto - 3);
				$('.detalle-noticias').css('height', alto);
			}
*/
/* ----------------------- */
/* <-- INICIO altoBloque() */
/* ----------------------- */


/* <-- desplegar */
/* *********************************** */


		}
			
		return false;
	});

	$("ul.lista-servicios a.link-servicios").click(function(){
		if ($(this).parent().hasClass('inactivo')||$(this).parent().hasClass('activo')) return false;
		
		cargaDesarrolloServicios($(this).attr('href'), $(this));
		return false;

/*
//alert($('.desarrollo-clientes').height() + $(this).parent().offset().top + ' ' + $('.desarrollo-clientes').parent().height())
		indiceLI = $(this).parent().parent().children('li').index($(this).parent())
		altoLI = $(this).parent().height();
		if ($('.desarrollo-servicios').height() + $(this).parent().offset().top < $('.desarrollo-servicios').parent().height() ) {
//			posTop = $(this).parent().offset().top - 119;
			posTop = 31 + ((altoLI + 1) * indiceLI);
		} else {
//			posTop = $(this).parent().offset().top - $(this).parent().height() - $('.desarrollo-clientes').height() + 8;
			posTop = ( 31 + ((altoLI + 1) * indiceLI) ) - $('.desarrollo-servicios').height() + 40;
		}
*/		
/*
		posTop = $(this).parent().offset().top - $('.desarrollo-servicios').parent().offset().top;
alert(posTop)
//		posTop = 31; 
		if ($('.desarrollo-servicios').height() + $(this).parent().offset().top < $('.desarrollo-servicios').parent().height() ) {
			//..
		} else {
			posTop = $(this).parent().offset().top - $(this).parent().height() - $('.desarrollo-clientes').height();
		}




		$('.desarrollo-servicios').css('top', posTop);
		$("ul.lista-servicios a.link-servicios").parent().addClass('inactivo', 1000);
//		$("ul.lista-clientes a.link-servicios").parent().children('.capa-fancy').fadeIn();
		$(this).parent().removeClass('inactivo').addClass('activo');
		$('.desarrollo-servicios').animate({'left': 'toggle'}, speedAbrirSubElemento);
*/
	});

/*
	$("ul.lista-servicios a.link-servicios.consultoria").click(function(){
		cargaDesarrolloServicios('consultoria.html', $(this));
	});
	$("ul.lista-servicios a.link-servicios.creatividad").click(function(){
		cargaDesarrolloServicios('creatividad.html', $(this));
	});
	$("ul.lista-servicios a.link-servicios.visual-thinking").click(function(){
		cargaDesarrolloServicios('visual-thinking.html', $(this));
	});
	$("ul.lista-servicios a.link-servicios.i-d-i").click(function(){
		cargaDesarrolloServicios('i-d-i.html', $(this));
	});
*/

	$("a.cerrar-desarrollo-servicios").click(function(){
		$('.desarrollo-servicios').animate({'left': 'toggle'}, speedCerrarSubElemento, function() {
			$("ul.lista-servicios a.link-servicios").parent().removeClass('inactivo');
			$("ul.lista-servicios a.link-servicios").parent().removeClass('activo');
		});
	});

	$("ul.lista-clientes a.link-servicios").click(function(){
		if ($(this).parent().hasClass('inactivo')||$(this).parent().hasClass('activo')) return false;
		
//alert($('.desarrollo-clientes').height() + $(this).parent().offset().top + ' ' + $('.desarrollo-clientes').parent().height())
		indiceLI = $(this).parent().parent().children('li').index($(this).parent())
		altoLI = $(this).parent().height();
		if ($('.desarrollo-clientes').height() + $(this).parent().offset().top < $('.desarrollo-clientes').parent().height() ) {
//			posTop = $(this).parent().offset().top - 119;
			posTop = 31 + ((altoLI + 1) * indiceLI);
		} else {
//			posTop = $(this).parent().offset().top - $(this).parent().height() - $('.desarrollo-clientes').height() + 8;
			posTop = ( 31 + ((altoLI + 1) * indiceLI) ) - $('.desarrollo-clientes').height() + 40;
		}
		$('.desarrollo-clientes').css('top', posTop);
		$("ul.lista-clientes a.link-servicios").parent().addClass('inactivo', 1000);
//		$("ul.lista-clientes a.link-servicios").parent().children('.capa-fancy').fadeIn();
		$(this).parent().removeClass('inactivo').addClass('activo');
		$('.desarrollo-clientes').animate({'left': 'toggle'}, speedAbrirSubElemento);
	});

	$("a.cerrar-desarrollo-clientes").click(function(){
		$('.desarrollo-clientes').animate({'left': 'toggle'}, speedCerrarSubElemento, function() {
			$("ul.lista-clientes a.link-servicios").parent().removeClass('inactivo');
			$("ul.lista-clientes a.link-servicios").parent().removeClass('activo');
		});
	});

	$("ul.lista-casos a.link-servicios").click(function(){
//		$('div[class^=bloque_]').css('display', 'none');
		
		//alert('va a cambiar la url');
		var url = $(this).attr("href");		
		//url = url.split('.')[0];		
		window.history.pushState(null, "", '?caso='+url);
		
		cargaCaso($(this));
		
/*
		topCerrarFull=$(this).offset().top + ($(this).height() / 2);
		leftCerrarFull=$(this).offset().left + ($(this).width() / 2);
		$('#div_casos_full').css({
//			'display': 'block',
			'z-index': '99',
			'top': topCerrarFull,
			'left': leftCerrarFull
		});
		$('#div_casos_full').stop(true).animate({
			'width': 'toggle',
			'width': 'toggle',
			'top': '24',
			'left': '37'
		}, speedAbrirFull, 'easeOutBack', function(){
//			$('.contenido_full .wrap-contenido-caso .imagen-caso').fadeIn('slow');
//				$('#div_casos_full').css('backgroundImage', 'url(img/bg-ejemplo-casos.jpg)');
//				$('#div_casos_full').stop(true).animate({'backgroundImage': 'url(img/bg-ejemplo-casos.jpg)'}, 500);
//				$('#div_casos_full').stop(true).animate({'backgroundPosition': '0'}, 500);
		})
*/
		return false;
	});

	$("#a-cerrar-full").click(function(){
		var href = window.location.href.split('?')[0];
		window.history.pushState(null, "", href);
		
//		$('div[class^=bloque_]').css('display', 'block');
//		$('#div_casos_full').css('display', 'none');		
		$('#div_casos_full').stop(true).animate({
			'height': 'toggle',
			'width': 'toggle',
			'top': topCerrarFull,
			'left': leftCerrarFull
		}, speedCerrarFull, 'swing', function(){
//			$('.contenido_full .wrap-contenido-caso .imagen-caso').css('display', 'none');
//				$('.contenido_full').css('backgroundImage', 'url(img/bg-ejemplo-casos.jpg)');
		})
	});

	$('.lista-sede').width($('.lista-sede').children('li').length * $('.lista-sede').children('li').width());

	$("#a-sede-cerrar-full").click(function(){
//		$('div[class^=bloque_]').css('display', 'block');
//		$('#div_casos_full').css('display', 'none');		
		$('#div_sede_full').stop(true).animate({
			'height': 'toggle',
			'width': 'toggle',
			'top': topCerrarFullSede,
			'left': leftCerrarFullSede
		}, speedCerrarFull, 'swing', function(){
//			$('.contenido_full .wrap-contenido-caso .imagen-caso').css('display', 'none');
//				$('.contenido_full').css('backgroundImage', 'url(img/bg-ejemplo-casos.jpg)');
		})
	});


	var indiceCarruselSede = 0;
	$("#a-sede-siguiente-full").click(function(){
		if (indiceCarruselSede == $('.lista-sede').children('li').length - 1) {
			return false;
		}
		
		indiceCarruselSede++;
		posLeft=( $('.lista-sede').children('li').width() * indiceCarruselSede ) * (-1);
		$('.lista-sede').animate({left: posLeft}, speedCarruselSede, function() {
			//cambiamos el texto del pie de foto.
			$('.pie-foto-sede span').html($('.lista-sede').children('li').eq(indiceCarruselSede).children('img').attr('alt'))
		})
		if (indiceCarruselSede == $('.lista-sede').children('li').length - 1) {
			$(this).fadeOut();
		} else {
			$(this).fadeIn();
		}
		if (indiceCarruselSede == 0) {
			$("#a-sede-anterior-full").fadeOut();
		} else {
			$("#a-sede-anterior-full").fadeIn();
		}


		return false;
	});

	$("#a-sede-anterior-full").click(function(){
		if (indiceCarruselSede == 0) {
			return false;
		}


		indiceCarruselSede--;
		posLeft=( $('.lista-sede').children('li').width() * indiceCarruselSede ) * (-1);
		$('.lista-sede').animate({left: posLeft}, speedCarruselSede, function() {
			//cambiamos el texto del pie de foto.
			$('.pie-foto-sede span').html($('.lista-sede').children('li').eq(indiceCarruselSede).children('img').attr('alt'))
		})
		if (indiceCarruselSede == 0) {
			$(this).fadeOut();
		} else {
			$(this).fadeIn();
		}
		if (indiceCarruselSede == $('.lista-sede').children('li').length - 1) {
			$("#a-sede-siguiente-full").fadeOut();
		} else {
			$("#a-sede-siguiente-full").fadeIn();
		}

		return false;
	});




	totalBloques = $('div[class^=bloque_]').length + 1;
	arrHeight = new Array(totalBloques);
	for (i=1;i<=totalBloques;i++){
		arrHeight[i] = $('.bloque_' + i).children('.contenido_bloque').height();
  }
	//añadimos un elemento más para la "pantalla" de detalle de noticia
	i++;
	arrHeight[i] = 0;
  
var resultado=arrHeight.length + " - <table width=200 border=1 cellpadding=1 cellspacing=1><tr>";
for (i=0;i<arrHeight.length;i++){
	resultado=resultado+"<td>" + arrHeight[i] + "</td>"
}
resultado=resultado+"</tr></table>" 
$('#contenido-array-height').html(resultado);
  
  

	$("div.interior-contacto li.redes-sociales a").mouseout(function(){
    	imagen=$(this).children('img').attr('src');
    	$(this).children('img').attr('src', imagen.substr(0, imagen.length - 7) + imagen.substr(imagen.length - 4))	
    }).mouseover(function(){
    	imagen=$(this).children('img').attr('src');
    	$(this).children('img').attr('src', imagen.substr(0, imagen.length - 4) + '-on' + imagen.substr(imagen.length - 4))	
    });


  
  //para que el bloque de noticias, que lleva un carrusel, mantenga su algo, se añaden aqui las propiedades css que hacen que funcione el carrusel
  $('.contenido_bloque.noticias').css('height', '100');
  $('.contenido_bloque.noticias .contenedor-noticias').css('position', 'absolute');

	$('.contenido_bloque.servicios').jScrollPane( { autoReinitialise: true } );
	$('.contenido_bloque.clientes').jScrollPane( { autoReinitialise: true } );
	$('.contenido_bloque.casos').jScrollPane( { autoReinitialise: true } );
	$('.contenido_bloque.manifiesto').jScrollPane( { autoReinitialise: true } );
	$('.contenido_bloque.sede').jScrollPane( { autoReinitialise: true } );
	$('.contenido_bloque.contacto').jScrollPane( { autoReinitialise: true } );
	$('.listado-noticias').jScrollPane( { autoReinitialise: true } );
	$('.detalle-noticias').jScrollPane( { autoReinitialise: true } );

/*
	o = $(".contenido_bloque").jScrollTouch();
*/
/*
	o = $(".contenido_bloque").overscroll({
		cancelOn: '.no-drag',
     showThumbs: true
	}).bind('overscroll:dragstart overscroll:dragend overscroll:driftstart overscroll:driftend', function(event){
		console.log(event.type);
	});
	$("#link").click(function(){
		if(!o.data("dragging")) {
			console.log("clicked!");
		} else {
			return false;
		}
	});  
*/

});

/* ******************************************************* */
/* ******************************************************* */
/* ************** inicio funciones *********************** */
/* ******************************************************* */
/* ******************************************************* */
function addListenerClickVinculosListadoNoticias() {
//alert($("a.vinculo-ampliar-noticia").length);			

	$("a.vinculo-ampliar-noticia").click(function(){
			//cargamos la noticia correspondiente
			url=$(this).attr('href');

 			if (url!="#") {
	 			$.ajax({
	        url: url,
	        async:true,
	        beforeSend: function(objeto){},
	        complete: function(objeto, exito){if(exito=="success"){}},
	        dataType: "html",
	        error: function(objeto, quepaso, otroobj){
	            alert("Error:" + quepaso + " - objeto: " + objeto + " - otroobj: " + otroobj);
	        },
	        success: function(datos){
//		     		$('.detalle-noticias').html(datos);

		     		$('.detalle-noticias .jspPane').html(datos);

//		     		$('.detalle-noticias').css('overflow', 'auto');
//						$('#div_detalle_noticia').jScrollPane( { autoReinitialise: true } );

	 					$('.contenedor-noticias').stop(true).animate({left: -470}, speedIrNoticia, function() {

/* ----------------------- */
/* INICIO altoBloque() --> */
/* ----------------------- */
							arrHeight[indiceBloque + 1] = $('.detalle-noticias .jspPane').height();

							altoBloque($('.desplegado'), false);
/*
							//redimensionamos la capa para que entre la noticia
							altoMaximo=$('.desplegado').offset().top  + $('.desplegado').parent().height() - 101 ;
							bloqueDesplegado=$('.desplegado').parent();
							if (bajoLogo(bloqueDesplegado)) {
								altoMaximo = altoMaximo - $('#div_logo_neo').height() + 10;
							}
							alto = $('.detalle-noticias .jspPane').height();

$('#alto-bloque-desplegado').html(alto + ' - ' + altoMaximo);
							if (alto > altoMaximo) alto = altoMaximo;

							bloqueDesplegado.children('.contenido_bloque').stop(true).animate({'height': alto}, speedRedimensionarbloques, function() {

								if (!bloqueDesplegado.children('.contenido_bloque').hasClass('noticias')) {
	// 								bloqueDesplegado.children('.contenido_bloque').css('overflow', 'auto');
	 							}
								$('.contenedor-noticias').css({'height': alto});
								$('#div_detalle_noticia').css('height', alto);

								arrHeight[bloqueDesplegado.attr('class').substr(7) + 1]= alto;

var resultado=arrHeight.length + ' - <table border="1" cellpadding="1" cellspacing="1"><tr>';
for (i=0;i<arrHeight.length;i++){
	resultado=resultado+"<td>" + arrHeight[i] + "</td>"
}
resultado=resultado+"</tr></table>" 
$('#contenido-array-height').html(resultado);
								

//								$('.listado-noticias').css('height', alto - 3);
		 					})
*/
/* ----------------------- */
/* <--FIN altoBloque()     */
/* ----------------------- */

	 						
	 					})
						$('.volver-noticia').fadeIn('slow');
						
	        },
	        timeout: 3000,
	        type: "GET"
				});
			}			
			return false;
	});
}

function altoBloque(vinculo, desplegar) {
	bloque = vinculo.parent();
	//CONSOLIDADO
	if (desplegar) {
		altoMaximo=bloque.offset().top - 70;
	}else{
		altoMaximo=vinculo.offset().top  + bloque.height() - 101 ;
	}
	if (bajoLogo(bloque)) {
		altoMaximo = altoMaximo - $('#div_logo_neo').height()  + 10;
	}
	indiceBloque = bloque.attr('class').substr(7);

	//si está abierta la "pantalla" de detalle de noticia...
	if (bloque.children('.contenido_bloque').hasClass('noticias') && $('.contenedor-noticias').position().left < 0) {
		alto = arrHeight[indiceBloque + 1];
	}else{ 
		alto = arrHeight[indiceBloque];
	}

	if (alto > altoMaximo) alto = altoMaximo;
	
	if (desplegar) {
$('#alto-bloque-desplegado').html('if [' + indiceBloque + '] ' + alto + ' - ' + altoMaximo);
		
		bloque.children('.contenido_bloque').stop(true).css({'height': alto});
		bloque.children('.contenido_bloque').stop(true).animate({'height': 'toggle'}, speedDesplegarBloques, 'easeOutBack', function() {});
	}else{
$('#alto-bloque-desplegado').html('else [' + indiceBloque + '] ' + alto + ' - ' + altoMaximo);
		bloque.children('.contenido_bloque').stop(true).animate({'height': alto}, speedRedimensionarbloques, function() {});
	}

	//mueveElementosPorEncima(bloque, true)
	//si el que está desplegado es el de noticias, tenemos que poner el alto también a los dos div´s interiores de listado y detalle
	if (bloque.children('.contenido_bloque').hasClass('noticias')) {
		$('.contenedor-noticias').css({'height': alto - 0, 'top': '0'});
		$('.detalle-noticias').css('height', alto);
		if ($('.contenedor-noticias').position().left >= 0) {
			$('.listado-noticias').css('height', alto - 3);
		}
	}

var resultado=arrHeight.length + ' - <table border="1" cellpadding="10" cellspacing="1"><tr>';
for (i=0;i<arrHeight.length;i++){
	resultado=resultado+"<td>" + arrHeight[i] + "</td>"
}
resultado=resultado+"</tr></table>" 
$('#contenido-array-height').html(resultado);

}

function bajoLogo(bloque) {
	var finalBloque;
	if (bloque.children('.contenido_bloque').hasClass('2bloques')&&bloque.attr('class')!=$('#div_contenido > div[class^=bloque_]:last-child').attr('class')) {
		finalBloque =	bloque.offset().left + 470;
	} else {
		finalBloque =	bloque.offset().left + bloque.width();
	}
	var anchoVentana  = $(window).width();
	var anchoLogo = $('#div_logo_neo').width() + 19;//37;
	return finalBloque > anchoVentana - anchoLogo
}

function cargaCaso(vinculo) {
	
	$.ajax({
    url: vinculo.attr('href'),
    async:true,
    beforeSend: function(objeto){},
    complete: function(objeto, exito){if(exito=="success"){}},
    dataType: "html",
    error: function(objeto, quepaso, otroobj){
        alert("Error:" + quepaso + " - objeto: " + objeto + " - otroobj: " + otroobj);
    },
    success: function(datos){
   		$('.ajax-caso').html(datos);
   		
			topCerrarFull=vinculo.offset().top + (vinculo.height() / 2);
			leftCerrarFull=vinculo.offset().left + (vinculo.width() / 2);
			$('#div_casos_full').css({
	/*			'display': 'block',*/
				'z-index': '99',
				'top': topCerrarFull,
				'left': leftCerrarFull
			});
			
			
/*			
			imagenCaso=$('.wrap-contenido-caso').css('backgroundImage')
			$('.wrap-contenido-caso').css('backgroundImage', '')

			//$('#div_casos_full').css('backgroundImage', imagenCaso);
			$('#div_casos_full').css('background', '#fff ' + imagenCaso + ' right bottom no-repeat');
*/
			$('#div_casos_full').stop(true).animate({
				'width': 'toggle',
				'width': 'toggle',
				'top': '24',
				'left': '37'
			}, speedAbrirFull, 'easeOutBack', function(){
	//			$('.contenido_full .wrap-contenido-caso .imagen-caso').fadeIn('slow');
	//				$('#div_casos_full').css('backgroundImage', 'url(img/bg-ejemplo-casos.jpg)');
	//				$('#div_casos_full').stop(true).animate({'backgroundImage': 'url(img/bg-ejemplo-casos.jpg)'}, 500);
	//				$('#div_casos_full').stop(true).animate({'backgroundPosition': '0'}, 500);
			})
   		
    },
    timeout: 3000,
	  type: "GET"
	});
}

function cargaDesarrolloServicios(url, vinculo) {
	$.ajax({
    url: url,
    async:true,
    beforeSend: function(objeto){},
    complete: function(objeto, exito){if(exito=="success"){}},
    dataType: "html",
    error: function(objeto, quepaso, otroobj){
        alert("Error:" + quepaso + " - objeto: " + objeto + " - otroobj: " + otroobj);
    },
    success: function(datos){
   		$('.contenido-desarrollo-servicios').html(datos);
   		
			posTop = vinculo.parent().offset().top - $('.desarrollo-servicios').parent().offset().top;
//		alert(posTop)
		//		posTop = 31; 
			if ($('.desarrollo-servicios').height() + vinculo.parent().offset().top < $('.desarrollo-servicios').parent().height() ) {
				//..
			} else {
				posTop = vinculo.parent().offset().top - $('.desarrollo-servicios').height() + 23;
					if  ($('.desarrollo-servicios').height() + vinculo.parent().offset().top > $('.desarrollo-servicios').parent().height()) {
//alert('se pasa del bloque por abajo');
						posTop = $('.desarrollo-servicios').parent().height() - $('.desarrollo-servicios').height() - 47;
						
					}
			}
		
			$('.desarrollo-servicios').css('top', posTop);
			$("ul.lista-servicios a.link-servicios").parent().addClass('inactivo', 1000);
		//		$("ul.lista-clientes a.link-servicios").parent().children('.capa-fancy').fadeIn();
			vinculo.parent().removeClass('inactivo').addClass('activo');
			$('.desarrollo-servicios').animate({'left': 'toggle'}, speedAbrirSubElemento);
   		
    },
    timeout: 3000,
	  type: "GET"
	});
}





function desPlegarBloque(bloque) {
/*
	vinculo=bloque.children('a.link-bloque');


	var finalBloque = 	bloque.offset().left + bloque.width();
//alert ("position final bloque: " + finalBloque);
	var anchoVentana  = $(window).width();
//alert ("ancho ventana: " + $(window).width());
	var anchoLogo = $('#div_logo_neo').width() + 37;
//alert ("ancho logo: " + anchoLogo);
//alert (finalBloque > anchoVentana - anchoLogo);


	vinculo.addClass('desplegado');
	//si el bloque es doble, ampliamos el ancho del botón
	if (bloque.children('.contenido_bloque').hasClass('2bloques')) {
		vinculo.addClass('bloquedoble');
		
		
		//si es el último lo desplazamos a la izquierda
		if (bloque.attr('class')==$('#div_contenido > div[class^=bloque_]:last-child').attr('class')) {
			posLeft=bloque.offset().left;
			posLeft=posLeft - 240
			bloque.css('left', posLeft);
		}
		//si es el bloque de contacto, usamos z-index para que contacto esté por encima de noticias.
	}
	bloque.css('z-index', '99');
	bloque.next().css('z-index', '0');					


	altoMaximo=bloque.offset().top - 70;
	if (bloque.children('.contenido_bloque').hasClass('noticias')) {
		//si es el bloque de noticias no vale con mirar el alto del hijo, hay que mirar más abajo puesto que hay un carrusel.
		alto = bloque.children('.contenido_bloque').children('.contenedor-noticias').children('.listado-noticias').children('ul').height();
		alto=1000;
	} else alto = bloque.children('.contenido_bloque').height(); 
		
//alert(alto + ' - ' + altoMaximo);			
	if (alto > altoMaximo) alto = altoMaximo;
	
	indiceHeight=bloque.attr('class').substr(7);
	indiceHeight--;
//	arrHeight[indiceHeight] = alto;
	
	
	bloque.children('.contenido_bloque').stop(true).css({'height': alto});
	bloque.children('.contenido_bloque').stop(true).animate({'height': 'toggle'}, 300);

	mueveElementosPorEncima(bloque, true, "")

$('#posicion-logo').html('NO noticias');

	if (bloque.children('.contenido_bloque').hasClass('noticias')) {
//$('#posicion-logo').html('NOTICIAS');
		$('.contenedor-noticias').css({'height': alto - 0, 'top': 0});
		$('.listado-noticias').css('height', alto - 3);
		$('.detalle-noticias').css('height', alto);
	}
*/	
}
function mueveElementosPorEncima(bloque, abrir, bloqueDesplegar) {
/*
	//si tiene algún bloque encima, lo arrastra hacia abajo.

	//buscamos la posición que ocupa en el array.
	indiceBloque = bloque.attr('class').substr(7);
	for (i=0;i<arrOrden.length;i++){
		for (j=0;j<arrOrden[i].length;j++){
	  	if (arrOrden[i][j]==indiceBloque) {
	  		fila=i;
	  		columna=j;  		
	    }
	  }
	}
	//recorremos los bloques que tiene encima. Y los subimos
	var haMovidoObjetos=false;
	var contadorBloques = 0;
	for (i=fila-1; i>=0; i--) {
	//alert(arrOrden[i][columna]);
		identificadorBloque = '.bloque_' + arrOrden[i][columna];
		if ($(identificadorBloque).offset()!=null) {
			haMovidoObjetos=true;
//alert(abrir + '|' + i + ':' + columna   + ' - HA ENCONTRADO')
			if (abrir) {				
				posBottom = $(window).height() - $(identificadorBloque).offset().top - 31 + alto ;
			} else {
				posBottom = $(window).height() - $(identificadorBloque).offset().top - 31 - alto ;
			}
			$(identificadorBloque).stop(true).animate({'bottom': posBottom}, 300, function() {

//alert(bloqueDesplegar);
				if (bloqueDesplegar!="") {
					desPlegarBloque(bloqueDesplegar);
				}
			});
							
		} else {
//alert(abrir + '|' + i + ':' + columna   + ' - no hay offset')
		}
		contadorBloques++
	}
	if (!haMovidoObjetos) {
		if (bloqueDesplegar!="") {
			desPlegarBloque(bloqueDesplegar);
		}
	}
*/
}


/*
function cargaListadoNoticias(vuelta) {
	//cargamos el listado de noticias
	url="listado-noticias.php";
	$.ajax({
    url: url,
    async:true,
    beforeSend: function(objeto){},
    complete: function(objeto, exito){if(exito=="success"){}},
    dataType: "html",
    error: function(objeto, quepaso, otroobj){
        alert("Error:" + quepaso + " - objeto: " + objeto + " - otroobj: " + otroobj);
    },
    success: function(datos){
    	if (!vuelta) {
    		$('.noticias').html(datos);
				addListenerClickVinculosListadoNoticias();    		
    	}
    	else {
				$('.volver-noticia').fadeOut('slow');
	  		$('.noticias').fadeOut('slow', function() {
	    		$('.noticias').html(datos);
					addListenerClickVinculosListadoNoticias();
	    		$('.noticias').fadeIn('slow');
					//activamos el botón volver;
	  		});
			}
    },
    timeout: 3000,
	  type: "GET"
	});
}
*/



function ordenaBloques (animacion, animacionLogo, inicio){
  var ventana_ancho = $(window).width();
  var ventana_alto = $(window).height();

	if (ventana_ancho < anchoMinimo) ventana_ancho = anchoMinimo;

$('#ancho-ventana').html(ventana_ancho);
$('#alto-ventana').html($(window).height());

	var totalBloques = $("#div_contenido > div").length;
	var anchoReal = ventana_ancho - (margen_lados * 2);
	
	var bloquesFilas = Math.floor(anchoReal / anchoBloques);
	if (bloquesFilas>totalBloques) { 
		bloquesFilas=totalBloques; 
		var numeroFilas = 1; 
		var elementosEnFila1 = bloquesFilas;
	} else {
		var numeroFilas = Math.ceil(totalBloques / bloquesFilas); 
		if (bloquesFilas==1) var elementosEnFila1 =  bloquesFilas;
		else var elementosEnFila1 = totalBloques % bloquesFilas;
	}
//	var arrOrden = new Array(numeroFilas - 1, bloquesFilas - 1);
/*
	var arrOrden = new Array(numeroFilas - 1);
	for (i=0;i<arrOrden.length;i++){
		var arrOrden = new Array(numeroFilas - 1);
	
	}
*/	
//	var arrOrden= new Array(new Array (numeroFilas - 1), new Array(bloquesFilas - 1));	
//	var arrOrden= new Array(new Array (numeroFilas), new Array(bloquesFilas));	
	arrOrden= new Array(numeroFilas);	
	arrPosicionInicial = new Array(totalBloques + 1);

//	arrHeight= new Array(totalBloques);	
	
	var indCol = bloquesFilas - 1
	var indRow = numeroFilas - 1
	arrOrden[indRow]=new Array(); 

	for (i=totalBloques; i>0; i--) {
		//vamos rellenando hacia atrás
		arrOrden[indRow][indCol] = i;

		indCol--;
		if (indCol<0) {
			indRow--;
			arrOrden[indRow]=new Array(); 

			if (indRow==0) {
				//estamos en la primera fila;
				indCol=elementosEnFila1 - 1;
			} else { 
				indCol=bloquesFilas - 1;
			}
		}
	}

var resultado="<table width=200 border=1 cellpadding=10 cellspacing=1>";
for (i=0;i<arrOrden.length;i++){
    resultado=resultado+"<tr>"
    for (j=0;j<arrOrden[i].length;j++){
       resultado=resultado+"<td>" + arrOrden[i][j] + "</td>"
    }
    resultado=resultado+"</tr>"
}
resultado=resultado+"</table>" 
$('#contenido-array').html(resultado);


	//colocamos los objetos en pantalla
	for (i=0;i<arrOrden.length;i++){
	  for (j=0;j<arrOrden[i].length;j++){
			posLeft = margen_lados + (anchoBloques * j);
			
			//si es el último bloque...
			if(i==arrOrden.length-1 && j==arrOrden[i].length-1) {
				//si está desplegado...
				if ($('#div_contenido > div.bloque_' + arrOrden[i][j] + ' .link-bloque').hasClass('desplegado')) {
					//es noticias y es doble, lo desplazamos a la izquierda			
					posLeft=posLeft - 240
				}
			}
/*			
			if ($('.desplegado').attr('class')==$('#div_contenido > div[class^=bloque_]:last-child').attr('class')) {
				posLeft=$('.desplegado').parent().offset().left;
				posLeft=posLeft - 240
 				bloqueDesplegado.css('left', posLeft);
			}
*/
			
			posTop = ventana_alto + 7 - margen_arriba - ((numeroFilas - i) * 41)
			posBottom = margen_arriba + 3 + ((numeroFilas - i - 1) * 41)

			if (inicio) {
				arrPosicionInicial[arrOrden[i][j]] = posBottom + '|' + posLeft;
			} else {


				if (!animacion) {
					$('#div_contenido > div.bloque_' + arrOrden[i][j]).css({
						'display':'block',
						'left': posLeft,  
						//'top': posTop
						'bottom': posBottom  
					});	
				} else {
					$('#div_contenido > div.bloque_' + arrOrden[i][j]).stop(true).animate({
						'left': posLeft,  
						//'top': posTop
						'bottom': posBottom  
					}, speedColocarBloques, 'easeOutBack', function() {
						//cambiamos el alto del bloque que esté abierto
						
//						$(this).fadeIn();
	
	
						if ($('.desplegado').parent().offset()!=null) {
					//		alto=  $(window).height() - $('.desplegado').parent().offset().top +  70;
	
	
	/* ----------------------- */
	/* INICIO altoBloque() --> */
	/* ----------------------- */
							altoBloque($('.desplegado'), false);
	/*
							altoMaximo=$('.desplegado').offset().top  + $('.desplegado').parent().height() - 101 ;
	//		  			altoMaximo=$('.desplegado').parent().offset().top + $('.desplegado').parent().height();
	
							bloqueDesplegado=$('.desplegado').parent();
	
							if (bajoLogo(bloqueDesplegado)) {
								altoMaximo = altoMaximo - $('#div_logo_neo').height() + 10;
							}
				
	
							//si está abierta la "pantalla" de detalle de noticia...
							if ($('.desplegado').parent().children('.contenido_bloque').hasClass('noticias') && $('.contenedor-noticias').position().left < 0) {
								alto = arrHeight[bloqueDesplegado.attr('class').substr(7) + 1];
	$('#alto-bloque-desplegado').html('if - ' + alto + ' - ' + altoMaximo);
							}else{ 
								alto = arrHeight[bloqueDesplegado.attr('class').substr(7)];
	$('#alto-bloque-desplegado').html('else - ' + alto + ' - ' + altoMaximo);
							}
	
	
	
							if (alto > altoMaximo) alto = altoMaximo;
	
	//$('#alto-bloque-desplegado').html(bloqueDesplegado.attr('class').substr(7));
	
	
							bloqueDesplegado.children('.contenido_bloque').stop(true).animate({'height': alto}, speedRedimensionarbloques, function() {
								if (!bloqueDesplegado.children('.contenido_bloque').hasClass('noticias')) {
	// 								bloqueDesplegado.children('.contenido_bloque').css('overflow', 'auto');
	 							}
							});
							
							//si el que está desplegado es el de noticias, tenemos que poner el alto también a los dos div´s interiores de listado y detalle
							if ($('.desplegado').parent().children('.contenido_bloque').hasClass('noticias')) {
	$('#posicion-logo').html('está desplegado el de noticias');
								$('.contenedor-noticias').css({'height': alto - 0, 'top': '0'});
								$('.listado-noticias').css('height', alto - 3);
								$('.detalle-noticias').css('height', alto);
							}
	*/
	/* ----------------------- */
	/* <--   FIN altoBloque()  */
	/* ----------------------- */
						}
				  });
				}
			}
	    resultado=resultado+"<td>" + arrOrden[i][j] + "</td>"
    }
    resultado=resultado+"</tr>"
	}
	
	
	//comprobamos si hay que colocar el logo.
	if (numeroFilas==1) {
//		posRight = ventana_ancho - margen_lados - (anchoBloques * totalBloques) + 6;
		posRight = ventana_ancho - margen_lados - (anchoBloques * totalBloques) -13;
$('#posicion-logo').html('right: ' + posRight);
		//colocamos el logo alineado con el ultimo bloque
		if (!animacionLogo) {
			$('#div_logo_neo').css({
				'right': posRight
			}, 500);
		} else {
			$('#div_logo_neo').stop(true).animate({
				'right': posRight
			}, speedColocarLogoNeo);
		}
	} else {
$('#posicion-logo').html('right: 37 --');
		//el logo tiene que ir arriba a la derecha.
		if (!animacionLogo) {
			$('#div_logo_neo').css({
			 	'right': 15//33
			}, 500);
		} else {
			$('#div_logo_neo').stop(true).animate({
			 	'right': 15//33
			}, speedColocarLogoNeo);
		}
	}
	
	//si está abierta la "ventana" de contenido a pantalla completa, cambiamos su tamaño.
	if ('#div_casos_full:display') {
		$('#div_casos_full').width(anchoReal);

		var altoReal = ventana_alto - (margen_arriba * 2);

		$('#div_casos_full').height(altoReal);
		
		//colocamos los botones "anterior" y "siguiente".
		$('#a-anterior-full').css('top', (altoReal / 2) - 1.5)
		$('#a-siguiente-full').css('top', (altoReal / 2) - 1.5)
	}

	//si está abierta la "ventana" de contenido a pantalla completa, cambiamos su tamaño.
	if ('#div_sede_full:display') {
		$('#div_sede_full').width(anchoReal);
		var altoReal = ventana_alto - (margen_arriba * 2);
		$('#div_sede_full').height(altoReal);
	}



/*
	//cambiamos el alto del bloque que esté abierto
	if ($('.desplegado').parent().offset()!=null) {
//		alto=  $(window).height() - $('.desplegado').parent().offset().top +  70;
		alto= $('.desplegado').parent().offset().top + $('.desplegado').parent().height();
$('#posicion-logo').html(alto);
		alto= alto - 70;
		$('.desplegado').parent().children('.contenido_bloque').stop(true).animate({'height': alto}, 500);
	}
*/
}

function ordenaBloquesInicio(numeroBloque) {
	var totalBloques = $("#div_contenido > div").length;
	if (numeroBloque>totalBloques) return false;

	var position=arrPosicionInicial[numeroBloque].split('|');


	$('#div_contenido > div.bloque_' + numeroBloque).css({
//			'display': 'block',  
			'left': position[1],  
			'bottom': position[0]-1  
	});	

//alert("1: " + position[0] + " - 2: " + $('#div_contenido > div.bloque_' + numeroBloque).offset().top);

	$('#div_contenido > div.bloque_' + numeroBloque + ' a.link-bloque').css('display', 'block');	

	$('#div_contenido > div.bloque_' + numeroBloque).stop(true).animate({
		'left': position[1],  
		'bottom': position[0]  
	}, speedColocarBloques, 'easeOutBack', function() {
		//$(this).fadeIn();
		ordenaBloquesInicio(numeroBloque + 1);
  });
  
} 

function plegarBloque(bloque, bloqueDesplegar) {

	bloque.children('.contenido_bloque').slideUp(300);

	vinculo=bloque.children('a.link-bloque');

/*
	//si está desplegado clientes...
	if (bloque.children('.contenido_bloque').hasClass('clientes')) {
		//..comprobamos si está abierto el desarrollo.
		if (bloque.children('.contenido_bloque').children('.desarrollo-clientes').css('display')=="block") {
			//si está abierto, lo cerramos.
			$("a.cerrar-desarrollo-clientes").click();
		}
	}	
*/
	//si está desplegado servicios...
	if (bloque.children('.contenido_bloque').hasClass('servicios')) {
		//..comprobamos si está abierto el desarrollo.
		if (bloque.children('.desarrollo-servicios').css('display')=="block") {
			//si está abierto, lo cerramos.
			$("a.cerrar-desarrollo-servicios").click();
		}
	}	

	vinculo.removeClass('desplegado');

	bloque.children('.contenido_bloque').stop(true).animate({'height': 'toggle'}, speedPlegarBloques, function() {

		//si es el ultimo, lo desplazamos hacia la derecha, para devolverlo a su sitio.
		//NOTA ERR: Aqui habría que asegurarse también de que además de ser el último, es doble.
		if (bloque.attr('class')==$('#div_contenido > div[class^=bloque_]:last-child').attr('class')) {
			posLeft=bloque.offset().left;
			posLeft=posLeft + 240
			bloque.css('left', posLeft);
		}
		vinculo.removeClass('bloquedoble');
	
		//si está desplegado noticias, nos aseguramos de que lo dejamos en la parte de listado y quitamos el botón volver.
		if (bloque.children('.contenido_bloque').hasClass('noticias')) {
			$('.contenedor-noticias').css({left: -0})
		  $('.volver-noticia').fadeOut('slow');
		}	

  });
	mueveElementosPorEncima(bloque, false, bloqueDesplegar)
	

}


function cargaCasoLOAD(vinculo) {
	
	$.ajax({
    url: vinculo,
    async:true,
    beforeSend: function(objeto){},
    complete: function(objeto, exito){if(exito=="success"){}},
    dataType: "html",
    error: function(objeto, quepaso, otroobj){
        alert("Error:" + quepaso + " - objeto: " + objeto + " - otroobj: " + otroobj);
    },
    success: function(datos){
   		$('.ajax-caso').html(datos);
   		
			//topCerrarFull=vinculo.offset().top + (vinculo.height() / 2);
			//leftCerrarFull=vinculo.offset().left + (vinculo.width() / 2);
			$('#div_casos_full').css({
	/*			'display': 'block',*/
				'z-index': '99',
				'top': topCerrarFull,
				'left': leftCerrarFull
			});
			
			
/*			
			imagenCaso=$('.wrap-contenido-caso').css('backgroundImage')
			$('.wrap-contenido-caso').css('backgroundImage', '')

			//$('#div_casos_full').css('backgroundImage', imagenCaso);
			$('#div_casos_full').css('background', '#fff ' + imagenCaso + ' right bottom no-repeat');
*/
			$('#div_casos_full').stop(true).animate({
				'width': 'toggle',
				'width': 'toggle',
				'top': '24',
				'left': '37'
			}, speedAbrirFull, 'easeOutBack', function(){
	//			$('.contenido_full .wrap-contenido-caso .imagen-caso').fadeIn('slow');
	//				$('#div_casos_full').css('backgroundImage', 'url(img/bg-ejemplo-casos.jpg)');
	//				$('#div_casos_full').stop(true).animate({'backgroundImage': 'url(img/bg-ejemplo-casos.jpg)'}, 500);
	//				$('#div_casos_full').stop(true).animate({'backgroundPosition': '0'}, 500);
			})
   		
    },
    timeout: 50000,
	  type: "GET"
	});
}

