/**
 * jQuery poppy thumb - Spawns a nice fullsize image from a thumbnail.
 * creates a wrapping DIV element, puts the picture inside, attaches shadows etc.
 * @author Oded Idan
 * @extends jQuery
 * @see ui.draggable.js
 */

jQuery.fn.poppyThumb = function(fullsizeUrl, options) {
	
	var self = this; // Scope reference
	
	jQuery(self).css("cursor","pointer"); // Make it visible - this is clickable!
	
	var thumbSize = { width : jQuery(this).width(), height : jQuery(this).height() }
	
	// Parse options!
		var o = (typeof options !== "undefined") ? options : {};
		loadingMsg = (typeof o["loadingMsg"] !== "undefined") ? o["loadingMsg"] : "...";
		loadingHint = (typeof o["loadingHint"] !== "undefined") ? o["loadingHint"] : "";
		maxWidth = (typeof o["maxWidth"] !== "undefined") ? o["maxWidth"] : "800";

	// Show hint
		if (loadingHint)
			jQuery(this).attr("title", loadingHint);

	// A mini-function which returns drop-shadow table rows
	var getShadowRow = function(type, width, height) {
		var row = jQuery("<tr></tr>");
		switch (type) {
			
			case 'top':
				row
					.append("<td><img src=\"/images/pop-up/LT.png\" /></td>")
					.append("<td><img src=\"/images/pop-up/T.png\" width=\""+ width +"px\" height='18' /></td>")
					.append("<td><img src=\"/images/pop-up/RT.png\" /></td>")
			break;
			
			case 'center':
				row
					.append("<td><img src=\"/images/pop-up/L.png\" height=\"" + height + "\" width='18' /></td>")
					.append("<td class=\"poppyThumbBody\"></td>")
					.append("<td><img src=\"/images/pop-up/R.png\" height=\"" + height + "\" width='18' /></td>")
			break;
			
			case 'bottom':
				row
					.append("<td><img src=\"/images/pop-up/LB.png\" /></td>")
					.append("<td><img src=\"/images/pop-up/B.png\" width=\""+ width +"px\" height='18' /></td>")
					.append("<td><img src=\"/images/pop-up/RB.png\" /></td>")
			break;
			
		}
			return row;
	}

	// Click actions
		jQuery(this).click(function() {
			if (jQuery(self).data("popped")) {
				jQuery(jQuery(self).data("popped")).trigger("click");
				return;
			}
			// create an image element based on the thumb src, query its height/width
			var fullsize = new Image();
			fullsize.src = fullsizeUrl;
			
			jQuery(this)
			.before("<div class=\"poppyLoadingMessage\">"+loadingMsg+"</div>");
			
			// Position the loading message in the middle of the thumb
			jQuery(".poppyLoadingMessage")
			.css({
				"position" : "absolute",
				"z-index" : "900",
				"top" : jQuery(self).offset().top,
				"left" : jQuery(self).offset().left,
				"width" : jQuery(self).width()})
				.fadeIn("normal");
			
			// IE LOAD HACK - sometimes it caches images... This would make it more difficult
			 if (jQuery.browser.msie)
              fullsize.src += '?' + (Math.round(512 * Math.random()) + "" + Math.round(512 * Math.random()));
			
			// FOLLOWING ACTIONS IN FULLSIZE ONLOAD EVENT:
			jQuery(fullsize).load(function() {
				
				jQuery(this).appendTo(document.body);
				
				// get full sizes
				var full_w = (this.width > maxWidth) ? maxWidth : this.width;
				var full_h = (this.width > maxWidth) ? Math.round(maxWidth/this.width * this.height) : this.height;
				var full_l = Math.round(jQuery(window).width() / 2 - (full_w/2));
				var full_t = (jQuery(window).height() / 2 - (full_h/2) > 0) ? Math.round(jQuery(window).height() / 2 - (full_h/2)) : 10;
				
				// unfade waiting element
				jQuery(self).fadeTo("fast",1);
				
				// Obtain a clone of the fullsize image - must do this for post-loaded animation :(
					
				jQuery(this)
					// Assign absolute positioning
					.css("position", "absolute")
					.css("z-index", "150")
					.css("left", jQuery(self).offset().left)
					.css("top", jQuery(self).offset().top)
					.width(thumbSize.width)
					.height(thumbSize.height)
				
					.css("cursor", "pointer")
				// Put in the center of the screen
				.animate( 
				{
						width : full_w,
						height : full_h,
						left : full_l,
						top : full_t
					}
						
					,"slow" // Speed...
					, function() { // CALLBACK FUNCTION:
						// 1) Removes 'Loading' message	
						jQuery(".poppyLoadingMessage").fadeOut("300", function() {
								jQuery(".poppyLoadingMessage").remove();
							});
							
						// 2) Adds shadows around the image
							// Create the wrapping element
							var wrapper = jQuery("<div class=\"poppyWrapper\"></div>");
							
							// Create the drop-shadow table
							var shadowbox = jQuery("<table cellspacing='0' cellpadding='0'></table>").appendTo(wrapper);
							
							// Append rows
							shadowbox.append(getShadowRow('top',full_w,full_h));
							shadowbox.append(getShadowRow('center',full_w,full_h));
							shadowbox.append(getShadowRow('bottom',full_w,full_h));
							
							// Insert wrapper
							wrapper
								.attr("id", Math.round(Math.random() * 9999999))
								.insertBefore(this)
								.css(
								{
									'position' : 'absolute',
									'display' : 'none',
									'left' : jQuery(this).offset().left - 18,
									'top' : jQuery(this).offset().top - 18
								}
								)
								.fadeIn(
								500
								, function() {
									if (typeof supersleight !== "undefined" && (jQuery.browser.msie) && (jQuery.browser.version < 7)) {
										supersleight.limitTo(wrapper.attr("id"));
										supersleight.run();
									}
								}
								);
								
								// IE is obviously wrong, so let's fix it up
								if (jQuery.browser.msie) {
									wrapper.css({
								  	"left": wrapper.offset().left - 4,
								  	"top": wrapper.offset().top - 4
								  });
								}
							
						
							// Add wrapper reference data for removal on click
							jQuery(this).data("wrapper", wrapper);
							
							// Add an X button.
							jQuery(this).each(
								// Hover on
								function() {
									if (!jQuery(this).data("closeButton")) {
										var self = this;
										var wrapperOffset = jQuery(this).data("wrapper").offset();
										var closeButton = jQuery("<img src=\"/images/pop-up/close.gif\" />")
											.css({
												"position" : "absolute",
												"z-index" : "901",
												"display" : 'none',
												"top" : full_t + 6,
												"left" : full_l + full_w - 26,
												
												"cursor" : 'pointer'
											})
											.click(function() { jQuery(self).trigger("click"); })
											.insertBefore(jQuery(this));
											
										jQuery(this).data("closeButton", closeButton);
									}
									// Wait 0.5 seconds, then fade in the X button
									setTimeout(function() { jQuery(self).data("closeButton").fadeIn(500) }, 500);
								}
							);
												
						}
						
					)
					
					// destroyable on click
					.click(function() { 
						jQuery(this)
							.data("wrapper")
							.add(jQuery(this).data("closeButton"))
							.add(this)
							.fadeOut("slow", 
								function() { jQuery(this).remove(); jQuery(self).removeData("popped"); }
							) 
						});
					
					// Set data saying the element exists
					jQuery(self).data("popped", this);
				});
			});
				
}
