var PhotoGallery = function() {
	
	// propriedades públicas
	var actualImage;
	var margin = 330;
	var visibleMargin = 90;
	var lightsOn = true;

	// ie doesn't like position().left. Chrome doesn't like css('left')
	function _getLeft(el){

		var result = el.attr('data-image-counter') * 83;
		return parseInt( result, 10 );

	}
	
	function _init(){
		if( $('.photo_gallery').length == 0 )
			return false;

		// Keyboard
		$(document).keydown(function(e){
			if( $('input:focus, select:focus, textarea:focus, submit:focus, p:focus').length > 0)
				return true;
			
		  if( e.keyCode == 37 ){ 
				setTimeout(function(){
					_previous('right');
				}, 30);
				return false;
		    } else if( e.keyCode == 39 ) {
				setTimeout(function(){
					_next('left');
				}, 30);
				return false;
			}
		});
		
		actualImage = $('.photo_gallery .thumbs_containner a.current').attr('data-image-counter');

		// mouse sobre thumbs mostra pequenas setas
		$('.thumbs').hover(
//			function(){ fadeIn( $('.thumbs_arrow'), 200 ); },
//			function(){ fadeOut( $('.thumbs_arrow'), 110 ); }
		);

		$('.arrow_mouse_hover').hover(
			function(){
				fadeIn( $(this).parent().find('.big_arrow_left, .big_arrow_right'), 500 );
				fadeIn( $('.lamp'), 500 );
			},
			function(){
				fadeOut( $(this).parent().find('.big_arrow_left, .big_arrow_right'), 250 );
				fadeOut( $('.lamp'), 250 );
			}
		);

		$('.big_arrow_left a').click( function(){ _previous() });
		$('.big_arrow_right a').click( function(){ _next(); });

		/* controls - lamp click */
		$('.lamp, .lamp_switch_on').click( function(){
			if( isIe() ){
				alert('O seu navegador, o Internet Explorer, não suporta esta funcionalidade.');
			} else if( lightsOn ){
				$('.news_gallery_darkness').show();
				$('.lamp').addClass('switched_off');
				lightsOn = false;
			} else {
				$('.news_gallery_darkness').hide();
				$('.lamp').removeClass('switched_off');
				lightsOn = true;
			}
		});

		$('.lamp').hover(
			function(){
				if( lightsOn )
					$('.lamp').addClass('switched_off');
				else
					$('.lamp').removeClass('switched_off');
			}, function(){
				if( lightsOn )
					$('.lamp').removeClass('switched_off');
				else
					$('.lamp').addClass('switched_off');
			}
		);
		
		$('.thumbs_arrow_left a').click( function(){ 
			_scrollThumbs( $('.photo_gallery .thumbs_containner'), "+="+margin );
		 });
		$('.thumbs_arrow_right a').click( function(){
			_scrollThumbs( $('.photo_gallery .thumbs_containner'), "-="+margin );
		});
		

		$('.photo_gallery .thumbs_containner .image a').click(function(){
			$('.photo_gallery .thumbs_containner a').removeClass('current');
			$(this).addClass('current');

			actualImage = $(this).attr('data-image-counter');
			$('.current_counting').html( parseInt(actualImage)+1 );
			
			var thumbs = $(this).parents('#news_gallery .thumbs_containner');
			var containner = thumbs.parent().parent();
			var thumbsLeft = thumbs.position().left;
			var containnerWidth = parseInt( containner.css('width') );
			
			var newLeft = thumbsLeft;
			
			var totalWidth = parseInt(thumbs.find('.image a').first().css('width'));
			totalWidth*= -(parseInt(thumbs.find('.image a').last().attr('data-image-counter'))+1);
			var leftOffset = _getLeft( $(this) ) + thumbsLeft;
			
//			$('.orange').html( _getLeft($(this) ) );
			
			if( leftOffset < (0 + visibleMargin ) ){
				newLeft = thumbsLeft - (leftOffset) + margin;
			}

			var rightOffset = leftOffset + ( parseInt($(this).css('width')) );
			if( rightOffset > (containnerWidth - visibleMargin) ){
				newLeft = containnerWidth - rightOffset + thumbsLeft - margin;
			}

//			$('.orange').html( rightOffset +  ' x ' + (containnerWidth - visibleMargin) + '  ' );
//			$('.orange').html( leftOffset + ' | '+  containnerWidth +  ' - ' + rightOffset + ' + ' + thumbsLeft + ' - ' + margin);
			
			_scrollThumbs(thumbs, newLeft);
			
			$('.photo_gallery .current_image img').css({ opacity: 0.5 });
//			$('.photo_gallery .current_image img').css('opacity', '0.5');
//			$('.photo_gallery .current_image img').css('filter', 'alpha(opacity=50)');
			
			var _this = $(this);
			var loadImg = function() {
				$('.photo_gallery .current_image img').attr('src', _this.attr('data-image-url'));
				$('.photo_gallery .current_image img').load(function(){
					$('.photo_gallery .current_image img').css({ opacity: 1 });
					$('.photo_gallery .current_image .description').html(_this.find('span.description').html() );
					_preload();
				});
			};
			
			setTimeout( loadImg, 10);
			
		});
		
		_preload();
		
	}
	
	function _scrollThumbs(thumbs, newLeft){
		if( parseInt(newLeft) > 0 )
			newLeft = 0;
	
		var fxInterval = 300;
		thumbs.stop().animate({left: newLeft}, fxInterval);
		

		setTimeout(function(){
			var containner = thumbs.parent().parent();
			var thumbsLeft = parseInt( thumbs.position().left );
			var containnerWidth = parseInt( containner.css('width') );
//			var leftOffset = $('.thumbs_containner').position().left + thumbsLeft;
//			var rightOffset = leftOffset + ( parseInt($('.thumbs_containner').css('width')) );
			
			// largura total, somando-se todas as imagens
			var totalWidth = parseInt(thumbs.find('.image a').first().css('width'));
			totalWidth*= -(parseInt(thumbs.find('.image a').last().attr('data-image-counter'))+1);
			// o máximo que left pode ser. totalWidth é negativo.
			var maxLeft = totalWidth+visibleMargin;

			// se passar do limite à direita
			if( -(totalWidth)>containnerWidth &&
				thumbsLeft < maxLeft )
			{
				thumbs.stop().animate({left: maxLeft}, 200);
			}
			// se passar do limite esquerdo, reseta left
			else if( thumbsLeft > 0 ){
				thumbs.stop().animate({left: 0}, 200);
			}
			// se tiver menos imagens que a largura (há espaços em branco), left sempre deverá
			// ser zero.
			else if( -(totalWidth)<containnerWidth &&
						thumbsLeft < 0 )
			{
				thumbs.stop().animate({left: 0}, 200);
			}

//			$('.orange').html( containnerWidth +  ' > ' + ' - ' + totalWidth + ' - ' );
//			$('.orange').append( thumbsLeft +  ' > ' + ' - ' + maxLeft + ' - ' + newLeft );
		}, fxInterval+20);

	}
	
	function _next(){
		var tmpActualImage = parseInt( $('.photo_gallery .thumbs_containner a.current').attr('data-image-counter') );
		tmpActualImage+= 1;
		var nextImage = $(".photo_gallery .thumbs_containner a[data-image-counter="+tmpActualImage+"]");
		
		if( nextImage.length == 0 )
			return false;
		
		nextImage.click();
	}

	function _previous(){
		var tmpActualImage = parseInt( $('.photo_gallery .thumbs_containner a.current').attr('data-image-counter') );
		tmpActualImage-= 1;
		var prevImage = $(".photo_gallery .thumbs_containner a[data-image-counter="+tmpActualImage+"]");
		
		if( prevImage.length == 0 )
			return false;
		
		prevImage.click();
	}
	
	function _preload(){
		var tmpActualImage = parseInt( $('.photo_gallery .thumbs_containner a.current').attr('data-image-counter') );
		var imgs = new Array();

		for( i=0; i<2; i++ ){
			tmpActualImage+= 1;
			var nextImage = $(".photo_gallery .thumbs_containner a[data-image-counter="+tmpActualImage+"]");
			if( nextImage.length == 0 )
				return false;
		
			imgs[i] = new Image();
			imgs[i].src = nextImage.attr('data-image-url');
		}
	}
	
	function request(){}
	
// métodos públicos, acessíveis externamente

	request.init = function(){
		_init();
	}

	request.next = function(){ _next(); }
	request.previous = function(){ _previous(); }
		
	return request;
}();

$.fx.prototype.cur = function(){
    if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
      return this.elem[ this.prop ];
    }
    var r = parseFloat( jQuery.css( this.elem, this.prop ) );
    return typeof r == 'undefined' ? 0 : r;
}
