/*
 * Pagery (jmc_resizr) - a jQuery plugin for binding image sizes to a parent element
 * Examples and documentation at: http://code.euphemize.net/jQuery/jmc_resizr/
 * Version: 0.1 (2010-03-04)
 * Copyright (c) 2010 Joel Courtney
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 * Requires: jQuery v1.3.2 or later
*/
(function($) {
    $.fn.jmc_resizr = function(settings) {
		var win = $(window);

        var defaults = {
			downsizeonly: false,
            cropType : 'full',
			binding : {
				vertical : 'center',
				horizontal : 'center'
			},
			addOffset : {
				vertical: 0,
				horizontal: 0
			},
            followBrowserSize :  true,
			parentElement : $('body'),
			callback: ''
        };

		var opts = {
			settings: $.extend({}, defaults, settings)
		};
		
		var resizeNode = function(el) {
			el = $(el);
			
			var el_height, el_width, orig_height = -1, orig_width = -1;
			
			// set ratio
			if(el.attr("width") && el.attr("height")){
				el_height = el.attr("height");
				el_width = el.attr("width");
			} else {
				el_height = el.height();
				el_width = el.width();
			}
			
			ratio = el_height / el_width;
			
			var win_h = win.height(), win_w = win.width();
			
			// TODO: Update with binding to a parent element
			if(opts.settings.parentElement != $('body')) {
				win_h = opts.settings.parentElement.height(), win_w = opts.settings.parentElement.width();
			}

			var settings = $.extend({},opts.settings);
			
			win_h += settings.addOffset.vertical;
			win_w += settings.addOffset.horizontal;
			switch(settings.cropType) {
				case 'fit':
					h = win_h;
					w = win_w;
					break;
				case 'height':
					h = win_h;
					w = win_h / ratio;
					break;
				case 'heightOnly':
					h = win_h;
					w = win_h / ratio;
					break;
				case 'width':
					h = win_w * ratio;
					w = win_w;
					break;
				case 'fill_outer':
					if(win_h/win_w <= ratio) {
						// Go by width
						h = win_w * ratio;
						w = win_w;
					} else {
						// Go by height
						h = win_h;
						w = win_h / ratio;
					}
					break;
				case 'full':
				default:
					if(win_h/win_w >= ratio) {
						// Go by width
						h = win_w * ratio;
						w = win_w;
					} else {
						// Go by height
						h = win_h;
						w = win_h / ratio;
					}
			}
			
			h = Math.ceil(h);
			w = Math.ceil(w);
			
			if ( settings.downsizeonly ){
				var orig = getOriginalImgSize(el);
				
				if ( h > orig.height || w > orig.width ){
					h = orig.height;
					w = orig.width;
				}
			}
			
			switch(settings.binding.vertical) {
				case 'top':
					t = 0;
					break;
				case 'bottom':
					t = (win_h - h);
					break;
				case 'center':
				default:
					t = (win_h - h)/2;
					break;
			}
			switch(settings.binding.horizontal) {
				case 'left':
					l = 0;
					break;
				case 'right':
					l = (win_w - w);
					break;
				case 'center':
				default:
					console.log((win_w - w)/2);
					l = (win_w - w)/2;
					break;
			}
			
			switch(settings.cropType) {
				case 'heightOnly':
					el.css({'height':h});
					break;
				default:
					// el.css({'height':h, 'width':w, 'position': 'absolute', 'top': t, 'left': l});	
					el.css({'height':h, 'width':w, 'position': 'absolute', 'top': t, 'left': l});
					break;
			}
			
			// call a callback function, and pass it the element
		    if(typeof settings.callback == 'function'){
		      	settings.callback.call(this, el);
		    }
		};

        var followBrowserResize = function(el) {
			if ($(el) == null) {
				return;
			}
			resizeNode(el);
        };

	    return this.each(function() { 
		
			var settings = $.extend({},opts.settings);
			
			// Check that it is an image
			if (this.nodeName === 'IMG') {
				// Undertake check load state
				$(this).load(function () {
					resizeNode(this);
			        if (settings.followBrowserSize) {
			            $(window).bind('resize', {el:this}, function(event) {
							followBrowserResize(event.data.el);
			            });
			        }
				}).error(function () {
	            // notify the user that the asset could not be loaded
					alert("Could not load!"+$(this).attr('src'));
		        }).attr('src', $(this).attr('src'));
	        } else {
				resizeNode(this);
		        if (settings.followBrowserSize) {
		            $(window).bind('resize', {el: this}, function(event) {
						followBrowserResize(event.data.el);
		            });
		        }
			}
			
	    });


        function getOriginalImgSize($img) {
            var t = new Image();
            t.src = $img.attr("src");
            return {width: t.width, height: t.height};
        }
	};
})(jQuery);
