$(function() {
	var api_key 			= 'fa473da3994a64a92da1f48a7eda2e8e';
	var user_id  			= '27700255@N07';
	
	/*
	use:
	Square,Thumbnail,Small,Medium or Original for the large image size you want to load!
	*/
	var large_image_size 	= 'Medium';
	/*
	the current Set id / the current Photo id
	*/
	var photo_set_id,photo_id;
	var esCargaInicial = true;
	var $setMarcadoActual;
	var $fotoMarcadaActual;
	var bloqueFotosActual = 0;
	var current	= 0;
	var tituloInicial = "";
	var continueNavigation = false;
	
	/*
	flickr API Call to get the Recent photo uploaded
	*/
	var recent_photo_service_home = 'http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos' + '&api_key=' + api_key + '&user_id=' + user_id + '&per_page=3&page=1&format=json&jsoncallback=?';
	var recent_photo_service_section = 'http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos' + '&api_key=' + api_key + '&user_id=' + user_id + '&per_page=60&page=1&format=json&jsoncallback=?';
	
	/*
	flickr API Call to get List of Sizes of a Photo
	*/
	var large_photo_service = 'http://api.flickr.com/services/rest/?&method=flickr.photos.getSizes' + '&api_key=' + api_key;
	
		
	/* 
	elements caching... 
	*/
	var $photoHomeContainer = $('#widgetFlickr');
	var $photoSectionContainer = $('#flickr_photobar');
	
	
	
	
	var ul_width,spacefit,fit;
	
	$(document).ready(function() {
		$photoHomeContainer.css("display", "none");
		$photoHomeContainer.fadeOut("0", "linear");
		
		LoadLargePhotoHome();
	});
	
	$('#photos').toggle(function(){
		LoadLargePhotosSection();
	},function(){
		//do nothing
	});
		
		
	function LoadLargePhotosSection(){
		
		var recent_photos_url	= recent_photo_service_section;
		$.getJSON(recent_photos_url, function(data){
			if(data.stat != 'fail') {
				var photo_count = data.photos.perpage;
				if(photo_count > 0){	
					
					var numFoto;
					var propiedadesTituloFoto = new Array(photo_count);
					var propiedadesIdFoto = new Array(photo_count);
					var propiedadesLargeUrls = new Array(photo_count);
					
					for (numFoto = 0; numFoto < photo_count; numFoto++) {
					
						var photo			= data.photos.photo[numFoto];						
						var phototitle		= photo.title;
						var photoid			= photo.id;
						
						propiedadesTituloFoto[numFoto] = phototitle;
						propiedadesIdFoto[numFoto] = photoid;						
						propiedadesLargeUrls[numFoto] = large_photo_service + "&photo_id=" + photoid + "&format=json&jsoncallback=?";
						
						var imgHtml = "<img id=\"seccion" + photoid + "\" title=\"" + phototitle + "\" src=\"\"";
						if (numFoto % 3 != 0){
							imgHtml = imgHtml + " style=\"margin-left:5.5px\"";
						}
						imgHtml = imgHtml + " />";
						
						$photoSectionContainer.append(imgHtml);						
					}
					
					$("#imagenClose").bind('click', function(e){
						$("#capaFotoCompleta").hide("fold", {}, 500, function (){
							$("#imagenBig").html("");
							$("#imagenBigTitulo").html("");
						});
					});
					
					for (numFoto = 0; numFoto < photo_count; numFoto++) {
						
						$.getJSON(propiedadesLargeUrls[numFoto], function(data){
							if(data.stat != 'fail') {
								
								var count_sizes = data.sizes.size.length;
								var largest_photo_src;
							
								for(var i = 0; i < count_sizes; ++i){
									if(data.sizes.size[i].label == large_image_size){
										largest_photo_src = data.sizes.size[i].source;
									}
								}
								
								var idFotoCargar = buscaIdFoto(propiedadesIdFoto, largest_photo_src);
								$("#seccion" + idFotoCargar).load(function(){
									var $this = $(this);									
									resizeSection($this);
																		
									$this.bind('click', function(e){
										
										$("#imagenBigTitulo").append($this.attr('title'));
										
										$("#capaFotoCompleta").show("fold", {}, 500, function() {
											
											$("<img title=\"" + $this.attr('title') + "\" />").load(function(){
												
												$(this).bind('click', function(e){
													$("#capaFotoCompleta").hide("fold", {}, 500, function (){
														$("#imagenBig").html("");
														$("#imagenBigTitulo").html("");
													});
												});
											
												resizeGaleria($(this));
												$("#imagenBig").append($(this));
												
												$(this).fadeIn(800);
											
											}).attr('src', $this.attr('src'));
											
										});	
										
									});
									
								}).attr('src', largest_photo_src);
							
							}							
						});
					}
					
					$photoSectionContainer.fadeIn("100", "linear");
				}
			}
		});
	}	
	
	function resizeSection($image){
		
		var windowW      = 313;
		var windowH      = 313;
		var theImage     = new Image();
		theImage.src     = $image.attr("src");
		var imgwidth     = theImage.width;
		var imgheight    = theImage.height;

		if((imgwidth > windowW)||(imgheight > windowH)){
			if(imgwidth > imgheight){
				var newwidth 	= windowW;
				var ratio 		= imgwidth / windowW;
				var newheight	= imgheight / ratio;
				theImage.height = newheight;
				theImage.width	= newwidth;
				if(newheight > windowH){
					var newnewheight = windowH;
					var newratio 	= newheight / windowH;
					var newnewwidth = newwidth / newratio;
					theImage.width 	= newnewwidth;
					theImage.height	= newnewheight;
				}
			} else {
				var newheight = windowH;
				var ratio = imgheight / windowH;
				var newwidth = imgwidth / ratio;
				theImage.height = newheight;
				theImage.width= newwidth;
				if(newwidth > windowW){
					var newnewwidth = windowW;
					var newratio = newwidth / windowW;
					var newnewheight = newheight / newratio;
					theImage.height = newnewheight;
					theImage.width= newnewwidth;
				}
			}
		}
		
		$image.css({'width':theImage.width+'px','height':theImage.height+'px'});
		$image.css({'margin-bottom':'0px', 'margin-top':'3px'});
		
	}
	
	function resizeGaleria($image){
		var widthMargin	 = 0; 
		var windowW      = $(window).width();
		var heightMargin = 0;
		var windowH      = $(window).height();
		var theImage     = new Image();
		theImage.src     = $image.attr("src");
		var imgwidth     = theImage.width;
		var imgheight    = theImage.height;

		if((imgwidth > windowW) || (imgheight > windowH)){
			if(imgwidth > imgheight){
				var newwidth 	= windowW;
				var ratio 		= imgwidth / windowW;
				var newheight	= imgheight / ratio;
				theImage.height = newheight;
				theImage.width	= newwidth;
				if(newheight > windowH){
					var newnewheight= windowH;
					var newratio 	= newheight/windowH;
					var newnewwidth = newwidth/newratio;
					theImage.width 	= newnewwidth;
					theImage.height	= newnewheight;
				}
			} else {
				var newheight = windowH;
				var ratio = imgheight / windowH;
				var newwidth = imgwidth / ratio;
				theImage.height = newheight;
				theImage.width= newwidth;
				if(newwidth > windowW){
					var newnewwidth = windowW;
					var newratio = newwidth/windowW;
					var newnewheight = newheight/newratio;
					theImage.height = newnewheight;
					theImage.width= newnewwidth;
				}
			}
		}
		
		//para calcular el margin que debemos dejar para centrar la imagen
		var sobranteW = windowW - theImage.width;
		var sobranteH = windowH - theImage.height;
		var marginW = (sobranteW / 2);
		var marginH = (sobranteH / 2) - 10; 
		
		$image.css({'width':theImage.width+'px','height':theImage.height+'px'});
		$image.css({'margin-left':marginW+'px','margin-top':marginH+'px'});
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////
	
	function LoadLargePhotoHome(){
		
		var recent_photos_url	= recent_photo_service_home;
		
		$.getJSON(recent_photos_url, function(data){
			if(data.stat != 'fail') {
				var photo_count = data.photos.perpage;
				if(photo_count <= 3){	
					
					var numeroFoto;
					var propiedadesTituloFoto = new Array(photo_count);
					var propiedadesIdFoto = new Array(photo_count);
					var propiedadesLargeUrls = new Array(photo_count);
					
					for (numeroFoto = 0; numeroFoto < 3; numeroFoto++) {
					
						var photo			= data.photos.photo[numeroFoto];
						var phototitle		= photo.title;
						var photoid			= photo.id;
						
						propiedadesTituloFoto[numeroFoto] = phototitle;
						propiedadesIdFoto[numeroFoto] = photoid;						
						propiedadesLargeUrls[numeroFoto] = large_photo_service + "&photo_id=" + photoid + "&format=json&jsoncallback=?";
						
						var imgHtml = "<img id=\"home" + photoid + "\" title=\"" + phototitle + "\" />";
						
						$photoHomeContainer.append(imgHtml);	
					}
					
					for (numeroFoto = 0; numeroFoto < photo_count; numeroFoto++) {	
						$.getJSON(propiedadesLargeUrls[numeroFoto], function(data){
							if(data.stat != 'fail') {
								var count_sizes = data.sizes.size.length;
								var largest_photo_src;
								var url;
								for(var i = 0; i < count_sizes; ++i){
									if(data.sizes.size[i].label == large_image_size){
										largest_photo_src 	= data.sizes.size[i].source;
										url = data.sizes.size[i].url;
									}
								}
								
								$("#home" + buscaIdFoto(propiedadesIdFoto, largest_photo_src)).load(function(){
									var $this = $(this);
									
									resizeHome($this);
									
									$this.bind('click', function(e){
										$("li#photosLi > a").click();
									});
								}).attr('src', largest_photo_src);
								
							}
							
						});
					
					}
					
					$photoHomeContainer.fadeIn("100", "linear");
				}
			}
		});
	}	
	
	function resizeHome($image){
		var widthMargin	 = 0; 
		var windowW      = 260 - widthMargin;
		var heightMargin = 0;
		var windowH      = 418 - heightMargin;		
		var theImage     = new Image();
		theImage.src     = $image.attr("src");
		var imgwidth     = theImage.width;
		var imgheight    = theImage.height;

		if((imgwidth > windowW) || (imgheight > windowH)){
			if(imgwidth > imgheight){
				var newwidth 	= windowW;
				var ratio 		= imgwidth / windowW;
				var newheight	= imgheight / ratio;
				theImage.height = newheight;
				theImage.width	= newwidth;
				if(newheight > windowH){
					var newnewheight= windowH;
					var newratio 	= newheight/windowH;
					var newnewwidth = newwidth/newratio;
					theImage.width 	= newnewwidth;
					theImage.height	= newnewheight;
				}
			} else {
				var newheight = windowH;
				var ratio = imgheight / windowH;
				var newwidth = imgwidth / ratio;
				theImage.height = newheight;
				theImage.width= newwidth;
				if(newwidth>windowW){
					var newnewwidth = windowW;
					var newratio = newwidth/windowW;
					var newnewheight = newheight/newratio;
					theImage.height = newnewheight;
					theImage.width= newnewwidth;
				}
			}
		}
		
		//para calcular el margin que debemos dejar para centrar la imagen
		var sobranteW = windowW - theImage.width;
		var sobranteH = windowH - theImage.height;
		var marginW = (sobranteW / 2);
		var marginH = (sobranteH / 2); 
		
		$image.css({'width':theImage.width+'px','height':theImage.height+'px'});
		$image.css({'margin-left':marginW+'px','margin-bottom':'0px'});
	}
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////
	
	function buscaIdFoto(fotosId, urlImagen){
	
		for (var i = 0; i < fotosId.length; i++){
			var partes = urlImagen.split(fotosId[i]);
			
			if (partes.length > 1) {
				return fotosId[i];
			}
		}
		
	}
	
});
