// --------------------------------------------------- //
// Utility Functions                                   //
// --------------------------------------------------- //

// ---
// Handles automatic sizing of images located in given dir that are referenced on the site
// This ensures that images uploaded outside our systems do not overflow content area
function ensureImageSizes() {
	
	// Configuration here
	config = {
		maxImgWidth: 450,
		minImgWidth: 50,
		fileLoc: '/userfiles/'
	};
	
	// Loop over all images on page
  $("img").each(function(i) {
		var element = $(this);
		
		// If the img is referencing a file in fileLoc, it's considered a file we need to
		// at least consider resizing. Here, we skip items that don't satisfy that requirement
		if ( element.attr("src").toUpperCase().indexOf(config.fileLoc.toUpperCase()) == -1 ) {
			return true; // skips to next iteration over loop
		}
		
		// Clear attributes and get good reading of width
		element.css('width', '');
		element.css('height', '');
		element.removeAttr('width');
		element.removeAttr('height');
		var width = element.attr('width');
		
		// If this image meets criteria for resizing
    if(width > config.maxImgWidth) {
			
			// Figure out how much we're taking off the size
      var reduceBy = width - config.maxImgWidth;
			
			// Attempt sizing down width, ensuring image still fits within minimum size 
      if(width - reduceBy >= config.minImgWidth) {
				element.attr('width', config.maxImgWidth);
			// Otherwise, size down to minimum and adjust reduceBy amount accordingly
			} else {
				element.attr('width', config.minImgWidth);
			}
			
    }
  });
}

