var smallImage = true;
var getImageData;
var updateZoomWindow;
var fixIEoverflow;
var thumbsExpandedWidth;

		// When the WINDOW is ready, initialize. We are going with
		// the window load rather than the document so that we
		// know our image will be ready as well (complete with
		// gettable dimentions).
		jQuery( window ).load(function(){

			// First, let's get refernces to the elements we will
			// be using.
			var view = jQuery( "#jqZoomDiv" );
			var image = jQuery( "#productImage" );
			
			//cashing of initial image
			var tmpAction = getCachedImageSrc(image.attr("src"));
			
			image.attr("galleryimg", "no");
			
			// Create the ZOOM element - this will be added with
			// Javascript since it's more of an "effect".
			//var zoom = jQuery( "<a id='zoom'><span><br /></span></a>" );
			var zoom = jQuery( "<a id='zoom'><span class='zoomCaption'></span><img src='" + staticRoot + "/img/white_pixel.gif' id='whitePixel' galleryimg='no'></a>" );
 
			// Before we start messing with the scripts, let's
			// update the display to allow for the absolute
			// positioning of the image and zoomer.
 
			// Set an explicit height / width on the view based
			// on the initial size of the image.
			view.width( image.width() );
			view.height( image.height() );
 
			// Now that the view has an explicit width and height,
			// we can change the displays for positioning.
			image.css( "position", "absolute" );
 
			// Set an exlicit height on the image (to make sure
			// that some of the later calcualtions don't get
			// messed up - I saw some irradic caculated-height
			// behavior).
			image.height( image.height() );
 
			// Before we add the zoom square, we need it to match
			// the aspect ratio of the image.
			
			updateZoomWindow = function() {
				jQuery("#zoom").width( Math.floor( jQuery( "#jqZoomDiv" ).width() / 2 ) );
				jQuery("#zoom").height( Math.floor( jQuery( "#jqZoomDiv" ).height() / 2 ) );
			}
 
			// Now, add the zoom square to the view.
			view.append( zoom );
			
			updateZoomWindow();
 
 
			// ---------------------------------------------- //
			// ---------------------------------------------- //
 
 
			// Now that we have our UI set up physically, we need
			// to bind the event handlers.
 
			// We want to show and hide the zoom only when the
			// user hovers over the view.
			view.hover(
				function( event ){
					// Show the soom.
					zoom.show();
				},
				function( event ){
					// Hide the zoom.
					zoom.hide();
				}
			);
 
 
			// As the user mouses over the view, we can get the
			// mouse coordinates in terms of the page; we need
			// to be able to translate those into VIEW-based
			// X and Y cooridates. As such, let's get the offset
			// of the view as our base 0x0 coordinate.
			//
			// NOTE: We are doing this here so that we do it once,
			// rather than every time the mouse moves.
			viewOffset = view.offset();
 
			// Get the jQuery-ed version of the window as we will
			// need to access it's scroll offsets every time the
			// mouse moves over the div.
			//
			// NOTE: This will change the change the refernce to
			// "window" for all of the code in this closure.
			var window = jQuery( window );
 
			// As the user moves across the view, we want to move
			// the zoom square with them.
			originalMouseMove = function( event ){
				// Get the window scroll top; the mouse
				// position is relative to the window, NOT
				// the document.
					var windowScrollTop = window.scrollTop();
					var windowScrollLeft = window.scrollLeft();
 
					// Translate the mouse X / Y into view-local
				// coordinates that can be used to position
				// the zoom box.
				setZoomPosition(
					Math.floor(
						event.clientX - view.offset().left + windowScrollLeft
					),
					Math.floor(
						event.clientY - view.offset().top + windowScrollTop
					)
				);
			}

			view.mousemove(
				originalMouseMove
			);
 
 
			// I position the zoom box within the view based on
			// the given view-local mouse coordinates.
			var setZoomPosition = function( mouseLeft, mouseTop ){
				// Ideally, we want to keep the zoom box centered
				// on the mouse. As such, we want the given mouse
				// left and mouse top coordiantes to be in the
				// middle of the zoom box.
				var zoomLeft = (mouseLeft - (zoom.width() / 2));
				var zoomTop = (mouseTop - (zoom.height() / 2))
 
				// As we move the zoom box around, however, we
				// never want it to go out of bounds of the view.
 
				// Protect the top-left bounds.
				zoomLeft = Math.max( zoomLeft, 0 );
				zoomTop = Math.max( zoomTop, 0 );
 
				// Protect the bottom-right bounds. Because the
				// bottom and right need to take the dimensions
				// of the zoom box into account, be sure to use
				// the outer width to include the border.
				zoomLeft = Math.min(
					zoomLeft,
					(view.width() - zoom.outerWidth())
					);
				zoomTop = Math.min(
					zoomTop,
					(view.height() - zoom.outerHeight())
					);
 
				// Position the zoom box in the bounds of the
				// image view box.
				zoom.css({
					left: (zoomLeft + "px"),
					top: (zoomTop + "px")
				});
			};
 
 
			// Now that we have the mouse movements being tracked
			// properly, we need to track the click on the zoom to
			// zoom in the image on demand. To do that, however,
			// we need to start storing some information with the
			// image so we can manipulate it as needed.
			
			
			// image data code for jQuery 1.3
			image.data("zoomFactor", (view.width() / zoom.width()));
			image.data("zoom", 1);
			image.data("top", 0);
			image.data("left", 0);
			image.data("width", image.width());
			image.data("height", image.height());
			image.data("originalWidth", image.width());
			image.data("originalHeight", image.height());
			image.data("originalViewLeft", view.position().left);
			
			// get the image data
			getImageData = function(img) {
				//imageData load for jQuery 1.2
				var imgDt = new Object();
				imgDt.zoom = img.data("zoom");
				imgDt.zoomFactor = img.data("zoomFactor");
				imgDt.top = img.data("top");
				imgDt.left = img.data("left");
				imgDt.width = img.data("width");
				imgDt.height = img.data("height");
				imgDt.originalWidth = img.data("originalWidth");
				imgDt.originalHeight = img.data("originalHeight");
				imgDt.originalViewLeft = img.data("originalViewLeft");
				
				/*
				//imageData load for jQuery 1.4
				var imageData = image.data();
				*/
				
				return imgDt;
			}
			
					
			/* image data code for jQuery 1.4
			image.data({
				zoomFactor: (view.width() / zoom.width()),
				zoom: 1,
				top: 0,
				left: 0,
				width: image.width(),
				height: image.height(),
				originalWidth: image.width(),
				originalHeight: image.height()
			});
			*/
 
			
			// Now, let's attach the click event handler to the
			// zoom box.
			/*zoom.parent().click(
				function( event ){
					alert("zoom.parent(); " + event.target.id);
					alert("zoom.position().left: " + zoom.position().left);
					alert("zoom.position().top: " + zoom.position().top);
				}
			);*/
			
			
			var clickFunc = function( event ){
				// First, prevent the default since this is
				// not a navigational link.
				event.preventDefault();

				// Let's pass the position of the zoom box
				// off to the function that is responsible
				// for zooming the image.
				var imageData = getImageData(image);
				if(imageData.zoom < 3) {
					zoomImage(
						zoom.position().left,
						zoom.position().top
					)
				} else {
					resetZoom(null, "true");
				}
			}
			
			// Because IE doesn't fire click event
			// of the zoom object it needs to be attached
			// to it's parent
			//zoom.parent().click(clickFunc);
			//zoom.click(clickFunc);
			
			// attach the drag functionality
			var drag = DragHandler.attach(document.getElementById('productImage'), originalMouseMove, clickFunc);
			
			// I take the zoom box coordinates and translate them
			// into an actual image zoom based on the existing
			// zoom and offset of the image.
			//
			// NOTE: We don't care about the dimensions of the
			// zoom box itself as those should have already been
			// properly translated into the zoom *factor*.
			var zoomImage = function( zoomLeft, zoomTop ){
				// Get a reference to the image data object so we
				// don't need to keep retreiving it.
				
				var imageData = getImageData(image);
				
 
				// Check to see if we have reached the max zoom
				// or if the image is currently animating.
				// If so, just return out.
				if (
					(imageData.zoom == 3) ||
					(image.is( ":animated" ))
					){
 
					// Zooming in beyond this is pointless (and
					// can cause the browser to mis-render the
					// image).
					return;
 
				}
				
				// calculate the zoomFactor before each zoom
				image.data("zoomFactor", (view.width() / zoom.width()));
				image.data("left", image.position().left);
				image.data("top", image.position().top);
				
				imageData = getImageData(image);
				
				// Scale the image up based on the zoom factor.
				imageData.width =
					((image.width()) * imageData.zoomFactor);
 
				imageData.height =
					((image.height()) * imageData.zoomFactor);
				
				// Change the offset set data to re-position the
				// 0,0 coordinate back up in the top left.
				imageData.left =
					((imageData.left - zoomLeft) * imageData.zoomFactor) + view.position().left;
 
				imageData.top =
					((imageData.top - zoomTop) * imageData.zoomFactor);
 
				// Increase the zoom.
				imageData.zoom++;
				image.data("zoom", imageData.zoom);
				
				// on first zoom level load the high definition image
				if (smallImage) {
					loadResizedImage();
				}
				
				var newViewWidth = Math.min(view.parent().width(), imageData.width);
				var newViewLeft = Math.max(0, (view.parent().width() - imageData.width)/2);
				var zoomLeft = zoom.position().left + Math.floor( (newViewWidth/2 - zoom.width())/2 );
				
				view.animate(
						{
							width: newViewWidth,
							left: newViewLeft
						},
						500,
						updateZoomWindow
					);
				
				zoom.animate(
						{
							width: Math.floor( newViewWidth / 2 ),
							left: zoomLeft
						},
						500
					);
				
				// Animate the zoom.
				image.animate(
					{
						width: imageData.width,
						height: imageData.height,
						left: Math.min(imageData.left, 0),
						top: imageData.top
					},
					500,
					fixIEoverflow
				);
				
			};
			
			fixIEoverflow = function() {
				view.css("overflow", "hidden");
			}
			
			// after the first zoom the high resolution image is loaded
			var loadResizedImage = function() {
				var wholeURL = image.attr("src");
				
				if(wholeURL.indexOf("?") != -1) {
					var imgURL = wholeURL.substr(0, wholeURL.indexOf("?"));
					var imgParams = wholeURL.substr(imgURL.length+1);
	
					if(imgParams.indexOf("sw=") != -1){
						var widthRegex = /sw\=\d+/i;
						imgParams = imgParams.replace(widthRegex, "sw=2000");
					} else {
						imgParams += "&sw=2000";
					}
					
					if(imgParams.indexOf("sh=") != -1){
						var heightRegex = /sh\=\d+/i;
						imgParams = imgParams.replace(heightRegex, "sh=2000");
					} else {
						imgParams += "&sh=2000";
					}
					
					wholeURL = imgURL + "?" + imgParams;
				} else {
					wholeURL = wholeURL += "?sw=2000&sh=2000"
				}
				
				smallImage = false;
				
				image.attr("src", getCachedImageSrc(wholeURL));
			}
			
			
			//*********************************
			// IMAGE NAVIGATOR CONTROLS
			//*********************************
			var closeBtn = jQuery("#closeButton");
			var openBtn = jQuery("#openButton");
			var thumbsContainer = jQuery("#imageSlideInner");
			
			// get thumbs container expanded width
			// and set it to hide everything that is wider
			thumbsExpandedWidth = thumbsContainer.width();
			thumbsContainer.css("overflow", "hidden");
			
			// changeScene7Styles for the open button
			openBtn.css("display", "none");
			openBtn.css("position", "static");
			
			// when close button is pressed all the images are hidden
			// and only the first one is displayed
			var closeImageNav = function( event ) {
				// First, prevent the default since this is
				// not a navigational link.
				event.preventDefault();
				
				// Animate the zoom.
				thumbsContainer.animate(
					{
						width: 56
					},
					500,
					function() { closeBtn.css("display", "none"); openBtn.css("display", "block"); }
				);
			}
			closeBtn.click(closeImageNav);
			
			
			// when open button is pressed all the images are shown
			var openImageNav = function( event ) {
				// First, prevent the default since this is
				// not a navigational link.
				event.preventDefault();
				
				// Animate the zoom.
				thumbsContainer.animate(
					{
						width: thumbsExpandedWidth
					},
					500,
					function() { closeBtn.css("display", "block"); openBtn.css("display", "none"); }
				);
			}
			openBtn.click(openImageNav);
			
		});
		
		
		function resetZoom(newURL, hideZoom, newAlt){
			var zoom = jQuery("#zoom");
			var image = jQuery( "#productImage" );
			
			// Get a reference to the image data object so we
			// don't need to keep retreiving it.
			
			// Reset the image data.
			image.data("zoom", 1);
			image.data("top", 0);
			image.data("left", 0);
			image.data("width", image.originalWidth);
			image.data("height", image.originalHeight);
			
			
			//var imageData = jQuery( "#productImage" ).data();
			var imageData = getImageData(image);
			var zoomLeft = zoom.position().left - Math.floor( (zoom.width() - imageData.width/2)/2 );

			if(hideZoom != undefined && hideZoom != null && hideZoom != 'false') {
				zoom.animate(
						{
							width: Math.floor(imageData.width/2),
							left: zoomLeft
						},
						300
					);
			}
			
			image.parent().animate(
					{
						width: imageData.width,
						left: imageData.originalViewLeft
					},
					300
				);

			// Animate the zoom.
			jQuery( image ).animate(
				{
					width: imageData.width,
					height: imageData.height,
					left: imageData.left,
					top: imageData.top
				},
				300,
				function() {
					if(newURL == null || image.attr("src").replace("sw=2000","sw=374").replace("sh=2000","sh=374") == newURL) {
						//reset to small image
						image.attr("src",image.attr("src").replace("sw=2000","sw=374").replace("sh=2000","sh=374"));
						smallImage = true;
					} else {
						if(!(image.attr("src") == newURL ) )
						{
							loadNewImage(newURL, newAlt);
						}
					}
					updateZoomWindow();
				}
			);
		};
		
		function loadNewImage(newImg, newAltText) {
			
			//replace the image by fade effect
			var newEle = jQuery("#productImage").clone().attr("src", getCachedImageSrc(newImg)).hide();
			
			jQuery("#productImage").after(newEle).fadeOut(100, function() {
				newEle.fadeIn(200,function() {
					jQuery("#productImage").attr("alt", newAltText);
					jQuery("#productImage").attr("title", newAltText);
					jQuery("#productImage").attr("src",jQuery(this).attr("src")).show('show', function() {
						newEle.remove();
					});
				})
			});
			
			smallImage = true;
		}
		
		// array is needed to identify that
		// image is cached
		var cachedImages = new Object();
		function getCachedImageSrc(srcUrl)
		{
			//image is already cached
			if(srcUrl in cachedImages) return srcUrl;
			var i = 0; 
			for(var item in cachedImages) {
				i++;
			}
			//going to cache the image
			cachedImages[srcUrl] = i + 1;
			var newImage =	jQuery("#productImage").clone().hide();
			newImage.attr("id","productImage_"+cachedImages[srcUrl]);
			newImage.attr("src",srcUrl);
			
			newImage.appendTo("body");
			
			return srcUrl;
		}

/**
*
*  Crossbrowser Drag Handler
*  
**/

var DragHandler = {
 
	// private property.
	_oElem : null,
	_oMouseMove : null,
	_zoom : null,
	_x : 0,
	_y : 0,
	_xAsis:false,
	_yAxis:false,
	
	// public method. Attach drag handler to an element.
	attach : function(oElem, oMouseMove, oClick) {
		DragHandler._oElem = oElem;
		DragHandler._oMouseMove = oMouseMove;
		DragHandler._zoom = oClick;
		
		jQuery('#jqZoomDiv').mousedown(DragHandler._dragBegin);

		return oElem;
	},
 
	// private method. Begin drag process.
	_dragBegin : function(e) {
		var oElem = DragHandler._oElem;
		
		if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
		if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
 
		var x =  parseInt(oElem.style.left);
		var y =  parseInt(oElem.style.top);
		
		e = e ? e : window.event;
		oElem.mouseX = e.clientX;
		oElem.mouseY = e.clientY;
		
		//get first click coordinates
		DragHandler._x = e.pageX;
		DragHandler._y = e.pageY;
		
		
		
		// determine on what axis the image will be moved 
		DragHandler._xAxis = (jQuery(oElem).width() > jQuery(oElem).parent().width());
		DragHandler._yAxis = (jQuery(oElem).height() > jQuery(oElem).parent().height());
		
		jQuery('#jqZoomDiv').mousemove(DragHandler._drag);
		jQuery(document).mouseup(DragHandler._dragEnd);
				
		return false;
	},

	// private method. Drag (move) element.
	_drag : function(e) {
		
		DragHandler._oMouseMove(e);
		
		//first zoom has not dragging
		var imageData = getImageData(jQuery("#productImage"));
		if( imageData.zoom == 1 ) {
			DragHandler._dragEnd(e);
			return false; 
		}
		
		jQuery('#jqZoomDiv').css("cursor","move");
		
		var oElem = DragHandler._oElem;
		
		var jQoElem = jQuery(DragHandler._oElem);
		
				
		var x = parseInt(oElem.style.left);
		var y = parseInt(oElem.style.top);
 
		e = e ? e : window.event;
		
		if(DragHandler._xAxis) {
			var newX = x + (e.clientX - oElem.mouseX);
			newX = Math.max(newX, jQoElem.parent().width() - jQoElem.width());
			newX = Math.min(newX, 0);
			oElem.style.left = newX + 'px';
		}
		
		if(DragHandler._yAxis) {
			var newY = y + (e.clientY - oElem.mouseY);
			newY = Math.max(newY, jQoElem.parent().height() - jQoElem.height());
			newY = Math.min(newY, 0);
			oElem.style.top = newY + 'px';
		}
 
		oElem.mouseX = e.clientX;
		oElem.mouseY = e.clientY;
 		
		return false;
	},
 
	// private method. Stop drag process.
	_dragEnd : function(e) {
		var oElem = DragHandler._oElem;
		
		var x = parseInt(oElem.style.left);
		var y = parseInt(oElem.style.top);
		
		//there is a click image have to be zoomed
		if(DragHandler._x == e.pageX && DragHandler._y == e.pageY)
		{
			DragHandler._zoom(e);
		}
		
		jQuery('#jqZoomDiv').css("cursor","default");
		
		jQuery('#jqZoomDiv').unbind('mousemove');
		jQuery('#jqZoomDiv').mousemove(DragHandler._oMouseMove);
		jQuery(document).unbind('mouseup');

	}
}
