/*
 * 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 img;
		
		var container;

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

		var opts = {
			settings: $.extend({}, defaults, settings)
		};

		var resizeNode = function() {
			console.log("resizeNode")
			
			el = $(img);
			console.log(el)
			
			if(!el){
				return
			}
			
			var settings = $.extend({},opts.settings);
			
			ratio = (el.height() ) / (el.width() ) ;
			
			if(!ratio){
				console.log("bad ratio")
				return
			}
			console.log(el)
			console.log( "ratio: " + ratio )
			
			//var win_h = win.height(), win_w = win.width();
			// TODO: Update with binding to a parent element
			// if(defaults.parentElement != $('body')) {
			// 	win_h = win.height(), win_w = win.width();
			// }
			
			console.log( el.parent() )
			var win_h = el.parent().height(), win_w = el.parent().width();
			console.log( "win_v: " + win_h, "win_w: " + win_w )
			
			
			var padding = $("#bg_img").outerHeight() - $("#bg_img").innerHeight()
			
			if (padding > 0){
				padding = padding / 2
			}
			
			console.log( "padding: " + padding )
			
			
			switch(settings.cropType) {
				case 'fit':
					h = win_h;
					w = win_w;
					break;
				case 'height':
					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;
					}
			}
			console.log( "h: " + h, "w: " + w )
			
			h = Math.ceil(h);
			w = Math.ceil(w);
			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:
					l = (win_w - w)/2;
					break;
			}
			el.css({'height':h, 'width':w, 'position': 'absolute', 'top': t -padding, 'left': l - padding});	
			console.log( h, w, t, l )
							
		};

        var followBrowserResize = function(el) {
	console.log("followBrowserResize")
			if ($(el) == null) {
				return;
			}
			resizeNode();
        };

		var imageLoaded = function(){
			
			console.log("image loaded: " )
			console.log($(img))
			//$(this).parent().hide()
			
			parent = $(img).parent()
			
			$(img).show()
			
			
			
			parent.fadeIn(2, function(){
				parent.show()				
				
				resizeNode()
				parent.hide()

				parent.fadeIn(1000)
				
			})
			
			
	
			
			console.log( $(img).width(), img.width )
			console.log( $( "#bg_img" ).width() )
			
			//$(this).parent().show()
			//resizeNode(this);
			resizeNode(img);
			
			//followBrowserResize( this )
			
			var settings = $.extend({},opts.settings);
	        if (settings.followBrowserSize) {
				el = img;
	            $(window).bind('resize', function() {
					followBrowserResize(el);
	            });
	        }

			
		}

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