// Carrusel de fotos con transici�n alfa
// Permite mostrar una secuencia de fotos con transici�n alfa 
// con carga eficiente en segundo plano. Opcionalmente el orden
// del carrusel sea aleatorio.
//
// Autor: Miguel Garc�a Dom�nguez
// Fecha: 15/06/2010
//
// Actualizacion: 02/11/2010 (imagenes cargadas como fondos de div por lo que se cortan por la derecha de la pantalla)

// Par�metros modificables:
var ruta_imagenes = "imagenes/header/";
var imagenes = ["01.jpg","02.jpg","03.jpg","04.jpg","05.jpg","06.jpg","07.jpg","08.jpg"];
var alto_imagenes = 130;
var orden_aleatorio = true;  // false si lo quieres siempre en ese orden
var tiempo_imagenes = 5; // tiempo que permanece cada imagen (en segundos)
var velocidad_transicion = 3000; // slow, normal o fast
// ------------------------------------------------------------------------------------//

// Variables globales:
var imagenes_cargadas = 0;
var id_interval;
var imagen_actual = 0;

// Detectar cuando el documento est� cargado:
$(document).ready(function() {	
	// Si se desea orden aleatorio, shuffle del array:
	if (orden_aleatorio) imagenes = shuffle(imagenes);
	
	// Se genera un poco de css para el contenedor:
	$("#carrusel").css("position","relative");
	
	// Se genera el html para el contenedor:
	var html = "";
	for (var i=0; i<imagenes.length; i++) {		
		html += '<div id="imagen_carrusel'+i+'" style="position:absolute; top:0; left:0; width:100%; height:' + alto_imagenes + 'px;"><img src=""></div>';
		html += '<img id="imagen_carrusel_oculta'+i+'" alt="'+i+'" style="display:none" />';
	}
	$("#carrusel").html(html);
	
	// Una vez cargada la imagen se cargan las dem�s:
	$("#imagen_carrusel_oculta0").load(function() {
		imagenes_cargadas++;
///		$("#imagen_carrusel0").css("background-image","url('"+ ruta_imagenes + "/" + imagenes[0] + "')");
		$("#imagen_carrusel0 img").attr("src",ruta_imagenes+"/"+imagenes[0]);
		for (var i=1; i<imagenes.length; i++) {		
			$("#imagen_carrusel_oculta"+i).load(function(obj) { 
				imagenes_cargadas++; 
				var index = $(obj.target).attr("alt");				
///				$("#imagen_carrusel"+index).css("background-image","url('"+ ruta_imagenes + "/" + imagenes[index] + "')");
				$("#imagen_carrusel"+index+" img").attr("src",ruta_imagenes + "/" + imagenes[index]);
			});
			$("#imagen_carrusel_oculta"+i).attr("src",ruta_imagenes + "/" + imagenes[i]);
			$("#imagen_carrusel"+i+" img").hide();						
		}
		
		// Se lanza un timer para controlar cuando las im�genes est�n cargadas:
		id_interval = setInterval(comprobarCarga,100);
	});
			
	// Se carga la primera imagen:
	$("#imagen_carrusel_oculta0").attr("src", ruta_imagenes + "/" + imagenes[0]);	
	
	posicionar();
  $.history.init(entrarSeccion);
  $(window).scroll(posicionar).resize(posicionar);
  posicionar();
  
});


// Funci�n para comprobar cu�ndo las im�genes est�n cargadas y lanzar el carrusel:
function comprobarCarga() {
	if (imagenes_cargadas >= imagenes.length) {
		clearInterval(id_interval);
		id_interval = setInterval(carrusel,tiempo_imagenes*1000);
	}
}


// Funci�n que efect�a el carrusel:
function carrusel() {
	var imagen_siguiente = (imagen_actual+1)%imagenes.length;
	$("#imagen_carrusel"+imagen_actual).css({'z-index': 2});
	$("#imagen_carrusel"+imagen_siguiente).css({'z-index': 1});
	
	$("#imagen_carrusel"+imagen_siguiente+" img").show();
	$("#imagen_carrusel"+imagen_actual+" img").fadeOut(velocidad_transicion);
	
	imagen_actual = imagen_siguiente;
}


// Funci�n para mezclar un array
// Jonas Raoni Soares Silva
// http://jsfromhell.com/array/shuffle [v1.0]
shuffle = function(o){ //v1.0
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};


function maxmin(valor,minimo,maximo)
{
  if (valor>maximo) return maximo;
  else if (valor<minimo) return minimo;
  else return valor;
}

function posicionar()
{
  vhc=maxmin($(window).height()-(500-100),100,350); 
  vhl=maxmin(vhc,100,173);
  
  if ($("#header").height()!=vhc)
  {

    $("#header").css("height",vhc+"px");
    $("#carrusel").css("height",vhc+"px");
    $("#carrusel div").css("height","350px");

    $("#logo").css("height",vhl+"px");
    $("#logo").css("top",(vhc-vhl+1)+"px");
    $("#logo img").css("height",vhl+"px");

  }
  
  vh=$(window).scrollTop()+$(window).height()-$("#pie").height();
  vh2=$("#menu1").height()+$("#cuerpo").height();
  if (vh<vh2) vh=vh2;
  if (vh<vh2) vh=vh2;
  $("#pie").css({position: "absolute",top:vh+"px"}); 
  
  // ajusta las im�genes de la cabecera al ancho
  var ancho=$(window).width();
  ancho=Math.max(ancho,$(document).width());
  var alto=ancho*350/1500;
  if (alto<vhc)
  {
    alto=vhc;
    ancho=vhc*1500/350;
  }
  var top=(vhc-alto)/2;
  var left=($(window).width()-ancho)/2;
  
  $("#carrusel div img").css("width",ancho);
  $("#carrusel div img").css("height",alto);
  $("#carrusel div").css("top",top+"px");
  $("#carrusel div").css("left",left+"px");

  
}

function entrarSeccion(vseccion)
{
  if (vseccion=="") vseccion="principal";
  
  vid="";
  temp=vseccion.split("/");
  if (temp.length==2)
  {
    vseccion=temp[0];
    vid=temp[1];
  };
    
  $(".activo").removeClass("activo");
  $("#seccion").stop().animate({opacity:0.1}, 500, function()
  {
      $("#seccion").load(vseccion+".php?id="+vid, function()
      {
        $("#menu_"+vseccion).addClass("activo");
        posicionar();
        $("#seccion").animate({opacity:1}, 500, function()
        {
          $("#seccion").removeAttr("filter");
          posicionar();
        });
      });
  });
}

