﻿
(function($) { // create closure

	//setup a namespace
	var nsp = 'a2b_ImagePopUp';

	//***************************************************
	// Main plugin method
	//***************************************************
	$.fn.a2b_ImagePopUp = function(options) {

		if (typeof options == 'string') {
			// we are triggering a method on an existing image
			var fn = $[nsp][options];
			if (!fn) {
				throw (nsp + " - No such method: " + options);
			}
			var args = $.makeArray(arguments).slice(1);
			return fn.apply(this, args);
		}

		return this.each(function() {
			if (this.a2b_ImagePopUp) {
				return; // Get out early - this target has already been initialized.
			}

			// Merge the supplied options with the defaults.
			var opts = $.extend({}, $[nsp].defaults, options || {});
			this.opts = opts;

			_.initializeWidget.call(this, opts);
			this.a2b_ImagePopUp = "Initialized";

		});
	};
	//***************************************************
	// End of Main plugin method
	//***************************************************

	// Public Members
	$[nsp] = {
		defaults: {
			sourceImage: null,
			maxWidth: 800,
			maxHeight: 600		
		}
	};

	// Private Members (in the "_" object)
	// NB: "this" will refer to "_" unless you use the call or apply methods
	var _ = {
		initializeWidget: function(opts) {
			if(!opts.sourceImage){
				opts.sourceImage = $(this);
			}
			_.ensureNaturalDimensions.call(this, opts.sourceImage[0]);
			$(this).bind("click", _.showImageInPopup);
		},
	
		showImageInPopup: function (){
			var imgElement = this.opts.sourceImage[0];
			var imgUrl = imgElement.src;
			var width = imgElement.naturalWidth;
			var height = imgElement.naturalHeight;				
            $.modal("<img src='"+ imgUrl +"' class='photo-large' />",
				{
					maxWidth:this.opts.maxWidth,
					maxHeight:this.opts.maxHeight,
					containerCss:{
						width:width, 
						height:height 
					}
				}
            );        
        },
        
		ensureNaturalDimensions: function (origImg) {			
			if(!origImg){
				return;
			}

			if (origImg.naturalWidth && origImg.naturalHeight) {
				return;
			}

			var url = $(origImg).attr("src");					
			$("<img id='dummy' src='" + url + "' />")
				.css({ width: "auto", height: "auto" })
				.appendTo(document.body)    // The width/height would be zero if img is not added to DOM.
				.load(function() {
					var $dummy = $(this);
					origImg.naturalWidth = this.width;
					origImg.naturalHeight = this.height;
					$dummy.remove();
				});
		}

	};

})(jQuery);         // end of closure
