// image-util.js

// Useful functions for manipulating images with javascript
// this file uses jquery

//A simple function to preload images
//its parameter is an array of image urls
function preload(sources, target, call)
{
  var images = [];
  nloaded = 0;
  nimages = sources.length;
  targ = target;
  $(targ).css('opacity', '0');
  for (i = sources.length-1; i >= 0; i--) {
    images[i] = new Image();
    images[i].src = "images/art/large/" + sources[i];
  }
  $(target).append(images);
  $(target + " img").attr("onload", "imageloaded("+call+")");
}

function imageloaded(cb){
	nloaded++;
	if(nloaded == nimages){
		$(targ).children('.preloading').remove();
		fitImages(targ);
		$(targ).animate({opacity:1, duration:600});
		if(cb != null){
			cb();
		}
	}
}

//Function to scale image's longest side to match parent container

function fitImages(targDiv, mode){
	var imgs = targDiv + " img";
	var imgWidth;
	var imgHeight;
	var imgRatio;
	var contWidth;
	var contHeight;
	var contRatio;
	var hpos = 'margin-left';
	var vpos = 'margin-top';
	
	if(mode == 'absolute'){
		hpos = 'left';
		vpos = 'top';
	}
	
	  
	  $(imgs).each(
		  function(){
			  imgWidth = $(this).css('width');// get inner dimensions of current img element
			  imgHeight = $(this).css('height');
			  
			  imgRatio = parseInt(imgWidth) / parseInt(imgHeight);
			  
			  
			  
			  contWidth = parseInt($(targDiv).css('width'));
			  contHeight = parseInt($(targDiv).css('height'));
			  
			  contRatio = parseInt(contWidth) / parseInt(contHeight);
			  			  
			  if(imgWidth>imgHeight){//landscape
				  if(imgRatio<contRatio){//if landscape but aspect ratio is less than that of container, scale by height
					  $(this).height(contHeight);
				  }
				  else{
					  $(this).width(contWidth);
				  }
			  }
			  else if(imgHeight>=imgWidth){//portrait or square
				  $(this).height(contHeight);
			  }
			  
			  //set left margin to horizontally center in parent
			  imgWidth = parseInt($(this).css('width'));
			  
			  var hDif = contWidth - imgWidth;// difference in widths
			  hDif/=2;
	  		  			  
			  $(this).css(hpos, hDif);
			  
			  //set top margin to horizontally center in parent
			  imgHeight = parseInt($(this).css('height'));
			  
			  var vDif = contHeight - imgHeight;// difference in heights
			  vDif/=2;
	  
			  $(this).css(vpos, vDif);
				
	});
}

