/* 

Resizify 0.1
	
Copyright (c) 2010, Robb Irrgang <robb@cartelblanche.com>
All rights reserved.

Please don't take the code and run with it, a proper open sourcing is coming soon. 

*/

(function($) {
    $.fn.extend({
		resizify: function(url, options) {
		var settings = $.extend({
			cache_folder: 'cache/resizify_',
			ratio: 4/3
		}, options);
		
		var image_url		= url;
		var image_ratio		= settings.ratio;
		var base_directory	= image_url.substr(0, image_url.lastIndexOf('/')+1);
		var base_file		= image_url.substr(image_url.lastIndexOf('/')+1);
		var base_extension	= base_file.substr(base_file.lastIndexOf('.'));
		var base_filename	= base_file.substr(0, base_file.length-base_extension.length);
		var ref				= this;
			
		var window_w;
		var window_h;
		var image_w;
		var image_h;
		var needed_w;
		var needed_h;  
		var resize_timeout;

		$(ref).hide();
			
		$(this).addClass('backdrop');						
			function setDimensions() {
				window_w = $(window).width();
				window_h = $(window).height();		
				
				image_w = window_w;
				image_h = Math.round(image_w/image_ratio);
				
				if (image_h < window_h) {
					image_h = window_h;
					image_w = Math.round(image_h*image_ratio);
				}
				
				needed_w = Math.ceil(image_w/256)*256;
				needed_h = Math.round(needed_w/image_ratio);
				
				if (needed_w > 2560) {
					needed_w = 2560;
					needed_h = Math.round(needed_w/image_ratio);
				}
				
				$(ref).find('img').get(0).width = image_w;
				$(ref).find('img').get(0).height = image_h;
				
				$(ref)
					.css('width', image_w+'px')
					.css('height', image_h+'px')
					.css('margin-left', -Math.round(image_w/2)+'px')
					.css('margin-top', -Math.round(image_h/2)+'px');
			}
			
			function loadImage(src, chainable) {
			var new_img = new Image();
				
				new_img.onload = function() {
					$(ref).html('<img src="'+src+'" alt="" title="" />');

					image_ratio = new_img.width/new_img.height;
					setDimensions();
					
					if (chainable) {
						chainable();
					} 
					
					$(ref).fadeIn('slow');
					
				};
				
				new_img.src = src;			
			}
			
			function loadProperImage() {
				loadImage(base_directory+settings.cache_folder+base_filename+'_'+needed_w+base_extension);
			}

			$(window).unbind('resize');

			$(window).bind('resize', function() { /* mod for faust */
				setDimensions();
				
				if (resize_timeout) {
					clearTimeout(resize_timeout);
					resize_timeout = false;
				}

				resize_timeout = setTimeout(function() { loadProperImage(); }, 1000);
			});

			return this.each(function() { //main
				loadImage(base_directory+settings.cache_folder+base_filename+'_768'+base_extension, loadProperImage);
			});
		}
	});
})($);

