$(function()
{		
	var CLIPING				  = {};
	CLIPING.opera			  = $.browser.opera;
	CLIPING.top_image_clip    = 104;
	CLIPING.clipImagesLoading = new Array();
	CLIPING.slcContentGalery  = 'div.media';
	CLIPING.slcImageGalery    = 'img.cliping';
	CLIPING.dMediasImgCliping = $(CLIPING.slcContentGalery+' '+CLIPING.slcImageGalery);		
	
	// INI: new styles in image galery
	$(CLIPING.slcContentGalery).css({
		//height	: TOP_IMAGE_CLIP+'px'
		height	: CLIPING.top_image_clip+'px'
	});
		
	CLIPING.dMediasImgCliping.css({
		position: 'absolute',
		bottom	: 0,
		display	: 'none'
	});
	
	$('img.plus,div.slideArea').css({
		display	: 'block'
	});
	// END: new styles in image galery
	
	// Inicializamos el array de control de carga (todas las imagenes a false, es decir, no estan cargadas por defecto)
	CLIPING.dMediasImgCliping.each(function(i){ CLIPING.clipImagesLoading[i] = false; });	
	
	// Iteramos todas las imagenes y ejecutamos una funcion anoamima recursiva que controla la carga de la imagen iterada.
	CLIPING.dMediasImgCliping.each(function(i)
	{
		img = this;		
		(function()
		{
			if (img.complete) 
				CLIPING.clipImagesLoading[i] = true; 
			else 
				setTimeout(arguments.callee,1);
		})();
	});
	
	
	// funcion anonima que gestiona el cliping de las imagenes	
	(function()
	{
		var iLoading = true;
		for(i=0;i<CLIPING.dMediasImgCliping.length;i++)
		{ 
			if (CLIPING.clipImagesLoading[i]==false) iLoading = false; 
		}
		
		// Mientras las imagenes no esten cargadas se va llamando a si misma
		if (!iLoading) setTimeout(arguments.callee,10);
		else
		{
			// Todas las imagenes estan cargadas
			(function() {			  	
				//Iteramos las capas que contienen las imagenes a las que se les aplica el cliping.													
				$( CLIPING.slcContentGalery ).each(function(i)
				{							
					var galery = this;
					var img = $(this).children(CLIPING.slcImageGalery);						
					
					img
						//Dejamos visible solo la primera
						.eq(0).show()
						// Iteramos las imagenes de la galeria iterada
						.each(function(){
							var w   = $(this).width();
							var h   = $(this).height();
							
							$(this).css( {clip: $.browser.msie ?
											'rect('+(h-CLIPING.top_image_clip)+'px '+w+'px '+h+'px 0px)' : 
											'rect('+(h-CLIPING.top_image_clip)+'px,'+w+'px,'+h+'px,0px)'} );
						});					
					
					$(this).children('a').click(function(e)
					{								
						if ( $(galery).attr('TOP') <= 0 )
							clipOn(galery);
						else
							clipOff(galery);
					});
					
					$(galery).find('a:first')
						.attr("href", img.eq(0)[0].src)
						.click(function(){return false;});
				});
			})();
		}
	})();
	
	// aEl -> div.media a
	function clipOff(galery) 
	{								
		img = $(galery).children(CLIPING.slcImageGalery+':visible');
		
		h = img.height();
		w = img.width();
		
		incremento = 100;
						
		$(galery).attr('TOP',h-CLIPING.top_image_clip);								
		
		$(galery).children('a').children('img.plus').attr({
				src   : '/media/img/common/iconos/minus.gif',
				alt   : '-',
				title : '-'
		});
																									
		$(galery).animate({height:h+'px'},200);			
		
		(function(){						// Se aplica cliping
			$(galery).attr('TOP', parseInt($(galery).attr('TOP')) - incremento);
			$(galery).children('img').css( { clip : $.browser.msie ? 
				'rect('+$(galery).attr('TOP')+'px '+w+'px '+h+'px 0px)' : 
				'rect('+$(galery).attr('TOP')+'px,'+w+'px,'+h+'px,0px)' } );							
			if ( $(galery).attr('TOP') > 0 ) setTimeout(arguments.callee, 0);
			else {
				if ( !CLIPING.opera )
				{
					setTimeout(function() { 
						$.scrollTo(galery,200);				
					},250);
				}
			}
		})();
		
		$(galery).children('div.slideArea').css("z-index",1);
	}
	
	function clipOn(galery) 
	{
		img = $(galery).children(CLIPING.slcImageGalery+':visible');
		h   = img.height();
		w   = img.width();
		
		//$(galery).attr('TOP',-10);
		$(galery).animate({height:CLIPING.top_image_clip+'px'},200,function()
		{
			$(galery).children('img').css( { clip : $.browser.msie ? 
				'rect('+(h-CLIPING.top_image_clip)+'px '+w+'px '+h+'px 0px)' : 
				'rect('+(h-CLIPING.top_image_clip)+'px,'+w+'px,'+h+'px,0px)' } );
			$(galery).attr('TOP',100);
			if ( !CLIPING.opera ) $.scrollTo($(galery).parents('div:first').offset()['top'],200);
		});

		$(galery)
			.find('a > img.plus') 
				.attr('src','/media/img/common/iconos/plus.gif')	// Cambiamos la imagen del link "minus" a "plus"
			.end()
				.children('.slideArea').css("z-index",-1);		// Escondemos el panel de "siguiente/anterior"
	}
	
	$("a.slidePrev, a.slideNext").click(function()
	{
		a 	   = this;
		dMedia = $(a).parents(CLIPING.slcContentGalery);
		iv     = $(a).parents('div.slideArea').prevAll(CLIPING.slcImageGalery+':visible');
		ni     = this.className == "slideNext" ? iv.next(CLIPING.slcImageGalery) : iv.prev(CLIPING.slcImageGalery);		
		
		if (!ni.length) {
			if ( a.className == 'slideNext' ) { 			// No hay siguiente
				ni = dMedia.children(CLIPING.slcImageGalery+':first');
				// la previa es la ultima
				iPrev = dMedia.children(CLIPING.slcImageGalery+':last');
				// la siguiente es la segunda
				iSiguiente = dMedia.children(CLIPING.slcImageGalery+':first').next();
			}
			else {											// No hay anterior
				ni = dMedia.children(CLIPING.slcImageGalery+':last');
				// la previa es la penultima
				iPrev = dMedia.children(CLIPING.slcImageGalery+':last').prev();
				// la siguiente es la primera
				iSiguiente = dMedia.children(CLIPING.slcImageGalery+':first');
			}
		}
		else {
			if ( a.className == 'slideNext' ) { 			// Si hay siguiente
				iPrev = ni.prev();
				iSiguiente = ni.next('img');
				if (!iSiguiente.length) iSiguiente = dMedia.children(CLIPING.slcImageGalery+':first');
			}
			else {											// Si hay anterior
				iSiguiente = ni.next();
				iPrev = ni.prev('img');
				if (!iPrev.length) iPrev = dMedia.children(CLIPING.slcImageGalery+':last');
			}
		}
		
		$(dMedia).find("a.slidePrev img,a.slideNext img, a img.plus").hide();
		
		if (!ni.size()) ni = this.className == "slideNext" ? dMedia.children(CLIPING.slcImageGalery+":first") : dMedia.children(CLIPING.slcImageGalery+":last");

		if (ni.size()) {
			$(ni).css("clip","rect(0px, "+ni.width()+"px, "+ni.height()+"px, 0px)");
			$(iv).fadeOut(200,function(){
				showLoading(dMedia);				
				$.scrollTo(dMedia[0].offsetTop - 25,0);
				dMedia.animate({height:ni.height()},500,function(){						
					hideLoading(dMedia);
					$(ni).fadeIn(500,function()
					{
						if ( !CLIPING.opera )
						{
							$.scrollTo(dMedia[0].offsetTop - 25,200);
						}
						
						$(dMedia)
							.find("a:first").attr("href", ni[0].src);
							
						$(a).parent().children('a.slideNext')
							.attr("href",iSiguiente[0].src)
							.click(function(){return false});
							
						$(a).parent().children('a.slidePrev')
							.attr("href",iPrev[0].src)
							.click(function(){return false});
						
						$(dMedia).find("a.slidePrev img,a.slideNext img, a img.plus").show();						
					});
				});
			});
		}			
	});
	
	function showLoading(el) {
		i = document.createElement('img');
		i.src = '/media/img/common/iconos/ajax-loader-big.gif';
		i.id="loaginGIF";
		i.style.marginTop = '50px';
		$(el).append(i);
	}
	
	function hideLoading(el) {
		$(el)[0].removeChild(document.getElementById("loaginGIF"));
	}
});