//Globales
var HEIGHT=0,WIDTH=0;
var $main;
var $image_layer;
var $image;
var $image_info;
var $cover;
var $buttons;
var image_preload;
var frames=0;
var $fps;
var $exif;
var timer = 0;
var IS_MOBILE = 'ontouchstart' in document;

//Constantes
var left_width = 100;
var gallery_height = 250;
var thumb_width = 270;

//Recoje el ancho y alto de la ventana, actualiza la posicion de la imagen
function resized(){
	HEIGHT = document.body.clientHeight;
	WIDTH = document.body.clientWidth - left_width;
	if (IMG.active) IMG.reallocate();
}

//Devuelve tamaņo imagen guardando aspecto
function redimage(ancho,alto,nAncho,nAlto){
	var w = ancho, h = alto, e = ancho/alto, f = nAncho/nAlto;
	if(nAncho<ancho || nAlto<alto){
		if ( (e>1 && e>=f) || (e<=1 && e>=f) ){ 
			w=nAncho;
			h=nAncho/e;
		}else{
			w=nAlto*e;
			h=nAlto;
		}
	}	 
	return {width:parseInt(w),height:parseInt(h)};
}

//Funciones de el expose
var ACT = {
	lastX : null,
	lastY : null,
	
	I:0,
	
	gals : [],
	destV : 0,
	curV : 0,
	
	mainH : 0,
	deathHor : .8,
	deathVer : 1,
	
	init : function(){
		ACT.mainH = $('.gallery').length * gallery_height;
		
		$('.gallery').each(function(i){
			ACT.gals[i] = { 
				$obj : $(this), 
				w : $(this).find('.thumb').length * thumb_width,
				curH : 0,
				destH : 0
			};
		});
		
		$('.thumb').each(function(){
			$(this).css({backgroundImage:'url(fotos/f'+this.id+'_thumb.jpg)'})
			.html('<div class="zoom"></<div>');
		})
		
		var mat = document.location.search.match(/\?foto=(\d+)/);
		
		if (mat && mat[1])
			$('#'+mat[1]+'.thumb').click();
			
			loop.start();
		if (IS_MOBILE){
			$(document).bind('touchmove',ACT.touchmove);
		}else{
			$('#container').mouseenter(ACT.enter).mousemove(ACT.move);
		}
	},
	
	touchmove : function(e){
		if (IMG.active) return true;
		e.preventDefault();
		var e = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];	
		
		var did = false;
		if (e.pageX!=ACT.lastX) {
			ACT.lastX = e.pageX;
			ACT.horizontal(e.pageX - left_width);
		}
		if (e.pageY!=ACT.lastY) {
			ACT.lastY = e.pageY;
			ACT.vertical(e.pageY);
		}
		
		return false;
	},
	
	move : function(e){
		//if (++ACT.I%4) return;
		if (IMG.active) return;
		var did = false;
		if (e.pageX!=ACT.lastX) {
			ACT.lastX = e.pageX;
			ACT.horizontal(e.pageX - left_width);
		}
		if (e.pageY!=ACT.lastY) {
			ACT.lastY = e.pageY;
			ACT.vertical(e.pageY);
		}
	},

	
	horizontal : function(pos){	
		var dif,ref,com,marginLeft;
		
		for(i in ACT.gals){
			dif = ACT.gals[i].w-WIDTH+20;				//Espacio no visible del main
			rel = ACT.deathHor;							//Zona muerta
			
			com = ((pos/WIDTH)*(1+rel))-(rel/2);		//Zona muerta aplicada a relacion posicion-espacio
			if (com<0) com=0; if (com>1) com=1;
			
			marginLeft = (-1*(com*dif));				//Margin aplicable a main
			if (marginLeft>0) marginLeft=0;	
			
			//ACT.gals[i].$obj.animate({marginLeft : marginLeft},{queue:false,duration:150,easing:'linear'});
			ACT.gals[i].destH = marginLeft;
		}
	},
	vertical : function(pos){
		var dif = ACT.mainH-HEIGHT+20;					//Espacio no visible del main
		var rel = ACT.deathVer;							//Zona muerta aplicada a relacion posicion-espacio
		
		var com = ((pos/HEIGHT)*(1+rel))-(rel/2);		//Zona muerta aplicada a rel
		if (com<0) com=0; if (com>1) com=1;
		
		var marginTop = (-1*(com*dif));					//Margin aplicable a main
		if (marginTop>0) marginTop=0;
		
		//$main.animate({marginTop : marginTop},{queue:false,duration:400,easing:'linear'});
		ACT.destV = marginTop;
	}	
}

//Funciones de la vision de la imagen
var IMG = {
	active:false,
	exifActive : false,
	galleryName : '',	
	
	getHref : function(alertIt){
		var href = document.location.href.replace(document.location.search,'')+'?foto='+$image.data('id')+'-'+$image.data('name').replace(/ /g,'-');
		if (alertIt==1) alert('Enlace a la foto:\n\n'+href);
		return href;
	},
	
	openLink : function(){
		var url = document.location.href.replace(document.location.search,'')+'fotos/f'+$image.data('id')+'_copy.jpg';
		window.open(url);
	},
	
	getExif : function(f,but){
		if (but && IMG.exifActive){
			$exif.addClass('hide');
			IMG.exifActive=false;
			return;	
		}
		IMG.exifActive=true;
		$exif.removeClass('hide').html('Cargando...');
		$.get('getExif.php',{id:$image.data('id'),f:f},function(data){
			$exif.html(data);	
		});
	},
	
	show : function(id,width,height,name){
		IMG.active = true;
		var $gal = $('#'+id).parent();
		IMG.galleryName = $gal.prev().text();
		
		$image.removeAttr('src')//.attr({src:'img/blank.gif'})
			//.attr({src:'../fotos/f'+id+'_full.jpg'})
			.data({id:id,width:width,height:height,name:name})
			.animate({opacity:1},200)
			.attr({src:'fotos/f'+id+'_full.jpg'});
		IMG.reallocate();
		
		if (IMG.exifActive) $exif.html('Cargando...')
		$image_layer.add($buttons).removeClass('hide').animate({opacity:1},500,function(){
			(new Image()).src = '../fotos/f'+IMG.next(1)+'_full.jpg';
			if (IMG.exifActive) IMG.getExif();
			loop.stop();
		});
		
	},
		
	reallocate : function(){
		var data = $image.data();
		var presize = redimage(data.width,data.height,990,660);
		var size = redimage(presize.width,presize.height,WIDTH-36-22,HEIGHT-80);
		
		var marginLeft = ((WIDTH-size.width)/2)+left_width-11;
		var marginTop = ((HEIGHT-size.height)/2);
		
		var href = IMG.getHref();
		$image_info.html(IMG.galleryName+'&nbsp;&nbsp;&gt;&nbsp;&nbsp;<a target="_blank" href="'+href+'" title="Enlace permanente">'+data.name+'</a>');
		
		$image.attr({width:size.width,height:size.height})
			.css({marginTop : marginTop , marginLeft : marginLeft });
	},
	
	hide : function(){
		IMG.active = false;
		$image_layer.add($buttons).stop().animate({opacity:0},500,function(){
			$(this).addClass('hide');
		});
		$exif.addClass('hide');
		loop.start();
	},
	
	next : function(justId){
		
		var cid = $image.data('id');
		var $current = $('#'+cid);
		var $next = $current.next();
		var nextId = 0;
		if (!(nextId = IMG.loadFollow($next,justId))){
			$current.parent().next('.gallery');
			$next = $current.parent().next().next().find('.thumb:first');
			if (!(nextId = IMG.loadFollow($next,justId)))
				if (justId!=1) IMG.hide();
		}
		return nextId;
	},
	
	prev : function(){
		
		var cid = $image.data('id');
		var $current = $('#'+cid);
		var $prev = $current.prev();
		if (!IMG.loadFollow($prev)){
			$current.parent().prev('.gallery');
			$prev = $current.parent().prev().prev().find('.thumb:last');
			if (!IMG.loadFollow($prev))
				IMG.hide();
		}
	},
	
	loadFollow : function($follow,justId){			
		if ($follow.length<1) return false;
				
		if (justId==1)
			return $follow.attr('id');
		else
			$image.stop().animate({opacity:0},200,function(){
				$follow.click();
			});
		
		return true;
	}
}


var keyPressed = {};
var tec = {
	37 : 'left',
	39 : 'right',
	40 : 'down',
	32 : 'space',
	38 : 'up',
	13 : 'enter',
	27 : 'escape',
	74 : 'j',
	72 : 'h',
	76 : 'l',
	69 : 'e',
	88 : 'x',
	73 : 'i'
};
function bindKeys(){
	$(document).keydown(function(e){
		if (tec[e.keyCode] && IMG.active){
			var key = tec[e.keyCode];
			if (!keyPressed[key]){
				keyPressed[key] = true;
				
				//Navegacion entre imagenes
				if (key=='space') IMG.next();
				if (key=='right' || key=='down') IMG.next();
				if (key=='left' || key=='up') IMG.prev();
				
				//Salir de Page
				if (key=='escape') IMG.hide();
				
				//Muestra link
				if (key=='l') IMG.getHref(1);
				
				//Muestra a tamaņo completo la imagen
				if (keyPressed['j'] && keyPressed['h']){
					keyPressed['j'] = false;
					keyPressed['h'] = false;    
					IMG.openLink();
				}
				
				//Muestra la informacion exif
				if (keyPressed['e'] && keyPressed['x']){
					keyPressed['e'] = false;
					keyPressed['x'] = false;
					IMG.getExif(1);
				}	
				
				//Muestra la informacion exif
				if (keyPressed['i']) IMG.getExif(0,1);
				
			}
		}
	});
	$(document).keyup(function(e){
		if (tec[e.keyCode]){
			var key = tec[e.keyCode];
			keyPressed[tec[e.keyCode]] = false;
		}
	});	
}

var loop = {
	timer : 0,
	smooth : 8,
	before : 0,
	last : 0,
	bucle : function(){
		var n = (ACT.destV - ACT.curV);
		if (abs(n)>0.1){
			ACT.curV += n / loop.smooth;
			$main[0].style.marginTop = (ACT.curV>>0)+'px';
		}
		for(var i=0,j=ACT.gals.length;i<j;i++){
			n = (ACT.gals[i].destH - ACT.gals[i].curH);
			if (abs(n)>0.1){
				ACT.gals[i].curH += n / loop.smooth;
				ACT.gals[i].$obj[0].style.marginLeft = (ACT.gals[i].curH>>0)+'px';
			}
		}
		if (fps.active){
			var curr = now()-loop.before;
			loop.before = now();
			loop.last += (curr-loop.last)/10;
		}
	},
	start : function(){
		loop.timer = setInterval(loop.bucle,1000/40);
	},
	stop : function(){
		clearTimeout(loop.timer);
	}
	
}

var fps = {
	active : false,
	$obj : [],
	init : function(){
		fps.$obj = $('<div id="fps" style="position:absolute;background-color:#fff;top:0;left:0;padding:6px;width:100px;font-size:18px;color:#900;font-family:monospace;"></div>').appendTo('body');
		fps.active = true;
		loop.before = now();
		setInterval(function(){
			fps.$obj.text((((1000/loop.last*100)>>0)/100));
		},60);
	}
}

function now(){ return (new Date()).getTime();}

function abs(x) {
	return (x < 0 ? -x : x);
}

$(function(){
	
	//Definicion de globales e iniciacion de opacidad
	$main = $('#main');
	$image_layer = $('#image_layer').css({opacity:0});
	$image = $('#image');
	$image_info = $('#image_info');
	$cover = $('#cover');
	$buttons = $('#buttons').css({opacity:0});
	$exif = $('#exif');
	
	//Binds
	$('#next').add($image).click(IMG.next);
	$('#prev').click(IMG.prev);
	$('#back').add($cover).click(IMG.hide);
	
	$('.thumb').click(function(e){
		var info = $(this).data('info').split('|');
		IMG.show(this.id,info[0],info[1],info[2]);
		e.preventDefault();
		return false;
	});
	
	ACT.init();	
	
	resized();
	window.onresize = resized;	
	
	bindKeys();
	
});
