SDNA.photos = {};

SDNA.photos.fitTo = function( img, fit ){
	
	var h = img.height;
	var w = img.width;
	var r = h/w;
	
	//fit image dimensions
	if( r <=1 && w > fit.width ){
		w = fit.width;
		h = Math.floor(w * r);
	}
	if( h > fit.height ){
		h = fit.height;
		w = Math.floor(h / r);
	}
	
	return {width:w,height:h};
}

SDNA.photos.zoom = function( opts ){
	
	//extend the options
	opts = $j.extend( {margin:15, caption: '', minWidth: 300}, opts );
	
	//show a loading indicator
	Window.block({loading:true});
	
	//preload the image
	var img = new Image();
	img.onload = function(){
		
		//add the title in
		var $caption 	= $j('<h2/>').text( opts.caption );
		var $container = $j('<div/>').addClass("image_box");	
		
		var captionHeight = $caption.height() + ( parseInt($caption.css('margin-bottom')) || 0 ) + ( parseInt($caption.css('margin-top')) || 0 );
		captionHeight = captionHeight == 0? 35: 0;

		var pad 		= opts.pad || 20;
		var marg 	= opts.margin;
		var win 		= Window.size();
		var fitTo 	= {width: win.width - marg*2 - pad*2, height: win.height - marg*2 - pad*2 - captionHeight };
		
		var fit 	= SDNA.photos.fitTo( img, fitTo );
		
		$img = $j(img);
		$img.attr( fit ).attr('alt',opts.title);
		
		$container.append( $img );
		
		fit.width = opts.minWidth > fit.width + pad? opts.minWidth : fit.width + pad;
		
		Window.pop( $container, { className: 'pop_photo', width: fit.width } );
		
	}
	
	img.onerror = function(){
		Window.pop( 'There was an error loading this image', {error: true });
	}
	
	//kick off the image load
	img.src = opts.src ;
}


SDNA.photos.bind = function(){
	
	//setup zoom
	$j('a.photo')
		.live('click.photo',
			function(e){
				
				//keep the image link from opening
				e.preventDefault();
				
				$this = $j(this);
				
				SDNA.photos.zoom( {src: $this.attr('href'), caption:$this.attr('title')} );				
			}		
	);	
}