/**
 * Author: Ryan Kahn
 * Date: 2010-03-30
 */

/**
 * Begins the image hider once the page loads
 */
Event.observe(window, 'load', hideImagesForWidth); 

/**
 * Calculates the width of the current container and hides images that cannot fit fully within that width
 * 
 */
function hideImagesForWidth(){
	//We are using ImageGrids for this feature... commonspot creates a class called CS_Element_ImageGrid which we use to identify
	var imageWidthContainers = $$(".CS_Element_ImageGrid, .imageHider");
	if(imageWidthContainers.size() > 0){ //If there are any containers
		//Register the window observer. read as: when window resizes call hideImagesForWidth (itself)
		Event.observe(window, 'resize', hideImagesForWidth);
		imageWidthContainers.each(function (container){//Iterate over each imageWidthContainer
			//Figure out our starting width
			var containerWidth = container.getWidth();
			//Get all the images in the container
			var images = $$("#"+container.identify()+" img");
			//Get a running total
			var remainingWidth = containerWidth;
			images.each(function (image){
				//The first part is finding out if this is the first time through. The first image should always be displayed
				//The second part is asking if there is enough space left for this image plus a 10px padding so we can be sure images wont wrap by the browser
				//The third part is when the image is REQUIRED to show
				if(remainingWidth > image.getWidth()+3 || image.hasAttribute("displayrequired")){
					//There was enough room or its the first image so subtract from the remaining width the width of the image
					remainingWidth = remainingWidth-(image.getWidth()+3);
					//Display the image
					image.show();
				}else{
					//Hide the rest
					image.hide();
				}
			});
		});
	}
}
