jQuery.fn.carrusel = function(){


	// VARIABLES
	var intervaloCarrusel;
	var listaEnlaces = $(this).find("a");
	var cantidadEnlaces = listaEnlaces.length;
	var fotoActual = 0;
	var fotoPrevia;
	var tiempoTransicion = 2000;
	var tiempoPausa = 4000;
	var intervaloEnMarcha = true;
	
	// LUPA
	$("#carruselFotos #controlesCarrusel").append("<div id='lupa'><img src='_img/ico_lupa.png'></div>");
	$("#lupa").css({ display:"block", height:"17px", width:"20px", position: "absolute", right:"4px", top:"-20px"  });
		
	// INIT
	$(listaEnlaces).each( function(){ $(this).css({ display:"block", height:"372px", width:"293px", position: "absolute", left:"0px", top:"0px", zIndex: "10" }); });
	$(".prevPic").click(prevImage);
	$(".nextPic").click(nextImage);
	$(".playPause").click(playPauseImage);
	$(this).parent().hover(muestraTip, ocultaTip);
	
	clearInterval(intervaloCarrusel);
	lanzaIntervalo();
	
	// INTERVALO
	function lanzaIntervalo(){
		if(intervaloEnMarcha){
			intervaloCarrusel = setInterval(nextImage, tiempoPausa);
		}
	}

	// CARRUSEL
	function cargaFoto(){
		clearInterval(intervaloCarrusel);
		var ruta = $(listaEnlaces[fotoActual]).attr("href");
		ruta = ruta.replace("large", "thumb");
			
		$(listaEnlaces).each( function(){ $(this).css({ zIndex: "10" }); });
		$(listaEnlaces[fotoPrevia]).css({ zIndex: "15"});
		$(listaEnlaces[fotoActual]).css({ zIndex: "20"}).hide();

		$(listaEnlaces[fotoActual]).find("img").attr("src", "").attr("src", ruta ).load(muestraFoto);
	}
	function muestraFoto(){
		$("#carruselFotos").css({ background:"none" })
		clearInterval(intervaloCarrusel);
		$(listaEnlaces[fotoActual]).fadeIn(tiempoTransicion, lanzaIntervalo);
	}

	// CONTROLES NAVEGACIÓN
	function nextImage(){
		if (fotoActual<cantidadEnlaces-1){ 
			fotoPrevia = fotoActual;
			fotoActual++; 
		} else {
			fotoPrevia = cantidadEnlaces-1;
			fotoActual=0; 
		}
		cargaFoto();
		return false;
	}
	function prevImage(){
		if (fotoActual>0){
			fotoPrevia = fotoActual; 
			fotoActual--; 
		} else { 
			fotoPrevia = 0;
			fotoActual=cantidadEnlaces-1;
		}
		cargaFoto();	
		return false;
	}
	function playPauseImage(){
		if (intervaloEnMarcha){
			intervaloEnMarcha = false;
			clearInterval(intervaloCarrusel);
			$(this).css({ backgroundPosition:"-30px 0px" });
		} else{
			intervaloEnMarcha = true;
			lanzaIntervalo();
			$(this).css({ backgroundPosition:"-15px 0px" });
		}
		return false;
	}

	// LUPA
	function muestraTip(){
		$("#carruselFotos #controlesCarrusel").css({ zIndex:"50"}).stop().animate({ bottom: "0px" }, 300);
	}
	function ocultaTip(){
		$("#carruselFotos #controlesCarrusel").stop().animate({ bottom: "-21px" }, 300);
	}
}
