var illZoom = {
    DEBUG: false,

    effectPending: false,
    imageRatio: null,
    largeWidth: null,
    largeHeight: null,
    targetPos: null,
    widthPad: null,
    heightPad: null,
    zoomActive: false,
    outsideBoxCount: 0,
    windowMouseMoveObserver: null,
    imgThumbBoxMouseOverObserver: null,
    isQuickView: false,
    imgThumbBoxWidth: null,
    imgThumbBoxHeight: null,
    zoomIndicatorWidth: null,
    zoomIndicatorHeight: null,
    zoomIndicator: null,
    zoomIndThumbImg: null,
    zoomBox: null,
    zoomImage: null,
    zoomImagePreloader: null,
    isSafari2: null,
    hideQtySelector: null,

    initZoom: function() {
        // Browser testing
        var safariSearchIndex = navigator.userAgent.indexOf("Safari");

        if(safariSearchIndex > -1) {
            var safariVersion = parseFloat(navigator.userAgent.substring(safariSearchIndex+"Safari".length+1));

            if(safariVersion < 500 && safariVersion > 0) {
                this.isSafari2 = true;
            }
        } else {
            this.isSafari2 = false;
        }
	      // Init Variables;
        this.effectPending = false;
        this.imageRatio = null;
        this.largeWidth = null;
        this.largeHeight = null;
        this.targetPos = null;
        this.widthPad = null;
        this.heightPad = null;
        this.zoomImage = null;
        this.zoomImagePreloader = null;
        this.zoomActive = false;
        this.outsideBoxCount = 0;
        this.windowMouseMoveObserver = null;
        this.imgThumbBoxWidth = null;
        this.imgThumbBoxHeight = null;
        this.zoomIndicatorWidth = null;
        this.zoomIndicatorHeight = null;
        this.hideQtySelector = null;

        this.zoomBox = $('zoomBox');

        /* Start: Experimental new stuff */
        this.zoomImagePreloader = document.createElement("img");
        this.zoomImage = document.createElement("img");
        this.zoomImage.style.position = "absolute";

        var zoomImagePreloaderContainer = document.createElement("div");
        zoomImagePreloaderContainer.style.overflow = "hidden";
        zoomImagePreloaderContainer.style.height = "0px";
        zoomImagePreloaderContainer.style.width = "0px";
        zoomImagePreloaderContainer.appendChild(this.zoomImagePreloader);
        document.body.appendChild(zoomImagePreloaderContainer);

        this.zoomBox.appendChild(this.zoomImage);

        this.targetPos = this.findPos($('imgThumbBox'));
        this.zoomBox.style.backgroundImage = "url('/sfModalBoxPlugin/css/spinner.gif')";

        this.widthPad = this.zoomBox.getDimensions().width/2;
        this.heightPad = this.zoomBox.getDimensions().height/2;

        this.zoomImagePreloader.src = $('imgThumbBox').name;

        // Properly Size the parent div
        $('imgThumbBox').parentNode.style.width = $('imgThumbBox').getDimensions().width + "px";
        $('imgThumbBox').parentNode.style.height = $('imgThumbBox').getDimensions().height + "px";

        // Add the zoomTintLayer
        var zoomTintLayer = document.createElement("div");
        zoomTintLayer.id = "zoomTintLayer";
        zoomTintLayer.style.position = "absolute";
        zoomTintLayer.style.background = "#000";
        zoomTintLayer.style.width = $('imgThumbBox').getDimensions().width + "px";
        zoomTintLayer.style.height = $('imgThumbBox').getDimensions().height + "px";
        zoomTintLayer.style.zIndex = 1001;

        this.imgThumbBoxMouseOverObserver = this.startZoom.bindAsEventListener(this);

        Event.observe(zoomTintLayer,
                      'mouseover',
                      this.imgThumbBoxMouseOverObserver);

        // Add the zoomIndicator
        this.zoomIndicator = document.createElement("div");
        this.zoomIndicator.id = "zoomIndicator";
        this.zoomIndicator.style.position = "absolute";
        this.zoomIndicator.style.overflow = "hidden";

        this.zoomIndThumbImg = document.createElement("img");
        this.zoomIndThumbImg.id = "zoomIndThumbImg";
        this.zoomIndThumbImg.src = $('imgThumbBox').src;
        this.zoomIndThumbImg.width = $('imgThumbBox').width;
        this.zoomIndThumbImg.height = $('imgThumbBox').height;
        this.zoomIndThumbImg.style.position = "absolute";
        // For IE
        this.zoomIndThumbImg.galleryimg = "no";

        this.zoomIndicator.appendChild(this.zoomIndThumbImg);

        zoomTintLayer.appendChild(this.zoomIndicator);

        //document.body.appendChild(zoomTintLayer);
        $('thumbBox').appendChild(zoomTintLayer);

        // For IE
        $('zoomTintLayer').setOpacity(0);

		// Wait for full size image to finish loading before calculating ratios
        Event.observe(this.zoomImagePreloader,
                      'load',
                      function() {illZoom.calculateRatios();});

         if(this.DEBUG) {
        	this.createDebugBox();
        }
    },

    /*
     * Once the large image has loaded calculate ratio between the images.
     */
    calculateRatios: function() {
        this.zoomImage.src = this.zoomImagePreloader.src;
        this.largeWidth = this.zoomImagePreloader.width;
        this.largeHeight = this.zoomImagePreloader.height;

        this.imageRatio = this.largeWidth / $('imgThumbBox').getDimensions().width;

        var zoomIndW = $('imgThumbBox').getDimensions().width * (this.zoomBox.getDimensions().width/this.largeWidth) + "px";
        var zoomIndH = $('imgThumbBox').getDimensions().height * (this.zoomBox.getDimensions().height/this.largeHeight) + "px";

        this.zoomIndicator.style.width = zoomIndW;
        this.zoomIndicator.style.height = zoomIndH;

        // Avoid uncessary recalculation
        this.imgThumbBoxWidth = $('imgThumbBox').getDimensions().width;
        this.imgThumbBoxHeight = $('imgThumbBox').getDimensions().height;
        this.zoomIndicatorWidth = $('zoomIndicator').getDimensions().width;
        this.zoomIndicatorHeight = $('zoomIndicator').getDimensions().height;
    },

    refreshImage: function() {
        this.zoomImagePreloader.src = $('imgThumbBox').name;
        this.zoomIndThumbImg.src = $('imgThumbBox').src;
    },

    startZoom: function(event) {
        this.targetPos = this.findPos($('imgThumbBox'));

        if(this.DEBUG) {
            $('debugBox').update(
                                "Target X: " + this.targetPos[0] + "<br/>" +
                                "Target Y: " + this.targetPos[1] + "<br/>" +
                                "Element scrolltop: " + document.documentElement.scrollTop + "<br/>" +
                                "Body scrolltop: " + document.body.scrollTop + "<br/>" +
                                "ZoomHeight: " + this.zoomBox.getDimensions().width
                            );
        }

        if(!this.effectPending && !this.zoomBox.visible()) 
        {
            $('zoomTintLayer').setOpacity(0.3);

            //effectPending = true;
            //new Effect.BlindRight('zoomBox', {duration: 0.2, fps: 100, afterFinish: function() { effectPending = false;}});

            if(null == this.hideQtySelector) {
                this.hideQtySelector = false;                 
            }

            if(this.hideQtySelector) {
                $('qtySelector').hide();
            }

            this.zoomBox.show();
            this.moveZoom(event);

            this.windowMouseMoveObserver = this.moveZoom.bindAsEventListener(this);

            Event.observe(document,
                          'mousemove',
                          this.windowMouseMoveObserver);

            Event.stopObserving('zoomTintLayer',
                                'mouseover',
                                this.imgThumbBoxMouseOverObserver);
        }
    },

    endZoom: function() {
        if(!this.effectPending && this.zoomBox.visible() && !this.zoomActive) {
            Event.stopObserving(document,
                                'mousemove',
                                this.windowMouseMoveObserver);

            // Make sure the modal window has not been closed
            if(!this.isQuickView || $('thumbBox')) {
                this.effectPending = true;


                new Effect.Fade('zoomBox',
                                {duration: 0.2,
                                 fps: 50,
                                 afterFinish: function() {
                                     illZoom.effectPending = false;

                                     if(illZoom.hideQtySelector) {
                                         $('qtySelector').show();
                                     }

                                     Event.observe('zoomTintLayer',
                                                   'mouseover',
                                                   illZoom.imgThumbBoxMouseOverObserver);
                                 }
                                }
                               );
                //this.zoomBox.hide();

                $('zoomTintLayer').setOpacity(0);
            }

            this.outsideBoxCount = 0;
        }
    },

    moveZoom: function(event) {
        var targX = this.targetPos[0] - (document.documentElement.scrollLeft + document.body.scrollLeft);

        if(this.isQuickView) {
            var targY = this.targetPos[1];
        } else {
            var targY = this.targetPos[1] - (document.documentElement.scrollTop + document.body.scrollTop);
        }

        if(this.isSafari2) {
            targY += document.body.scrollTop;
        }

        var desX = event.clientX - targX;
        var desY = event.clientY - targY;

        if(desX >= 0 && desX <= this.imgThumbBoxWidth &&
           desY >= 0 && desY <= this.imgThumbBoxHeight) {

            this.outsideBoxCount = 0;

            desX = desX * this.imageRatio;
            desY = desY * this.imageRatio;

            if(desX < this.widthPad) {
                desX = this.widthPad;
            } else if(desX > (this.largeWidth-this.widthPad)) {
                desX = this.largeWidth - this.widthPad;
            }

            if(desY < this.heightPad) {
                desY = this.heightPad;
            } else if(desY > (this.largeHeight-this.heightPad)) {
                desY = this.largeHeight - this.heightPad;
            }

            var bgX = (0 - desX) + this.widthPad;
            var bgY = (0 - desY) + this.heightPad;

            if(this.DEBUG) {
    	        $('debugBox').update(
    	                            "Target X: " + targX + "<br/>" +
    	                            "Target Y: " + targY + "<br/>" +
    	                            "Client X: " + event.clientX + "<br/>" +
    	                            "Client Y: " + event.clientY + "<br/>" +
                                    "Desired X: " + desX + "<br/>" +
                                    "Desired Y: " + desY + "<br/>" +
                                    "Background X: " + bgX + "<br/>" +
                                    "Background Y: " + bgY + "<br/>" +
                                    "Imageratio: " + this.imageRatio + "<br/>" +
                                    "Element scrolltop: " + document.documentElement.scrollTop + "<br/>" +
                                    "Body scrolltop: " + document.body.scrollTop + "<br/>" +
    	                            "ZoomHeight: " + this.zoomBox.getDimensions().width
    	                        );
            }

            this.zoomImage.style.left = bgX + "px";
            this.zoomImage.style.top = bgY + "px";

            //Move the zoom indicator with the cursor
            var zoomIndY = (event.clientY - targY) - this.zoomIndicatorHeight/2;
            var zoomIndX = (event.clientX - targX) - this.zoomIndicatorWidth/2;

            if(zoomIndY >= -1) {
                if(zoomIndY > this.imgThumbBoxHeight - this.zoomIndicatorHeight) {
                    zoomIndY = this.imgThumbBoxHeight - this.zoomIndicatorHeight;
                }
            } else {
                zoomIndY = -1;
            }

            if(zoomIndX >= -1) {
                if(zoomIndX > this.imgThumbBoxWidth - this.zoomIndicatorWidth) {
                    zoomIndX = this.imgThumbBoxWidth - this.zoomIndicatorWidth;
                }
            } else {
                zoomIndX = -1;
            }

            this.zoomIndicator.style.top = zoomIndY + "px";
            this.zoomIndicator.style.left = zoomIndX + "px";

            this.zoomIndThumbImg.style.top = (-zoomIndY - 1) + "px";
            this.zoomIndThumbImg.style.left = (-zoomIndX - 1) + "px";
        } else {
            this.outsideBoxCount++;

            if(this.outsideBoxCount > 10) {
                this.endZoom();
            }
        }
    },

    findPos: function(obj) {
    	var curleft = curtop = 0;
    	if (obj.offsetParent) {
    		curleft = obj.offsetLeft;
    		curtop = obj.offsetTop;
    		while (obj = obj.offsetParent) {
    			curleft += obj.offsetLeft;
    			curtop += obj.offsetTop;
    		}
    	}
    	return [curleft,curtop];
    },

    createDebugBox: function() {
       var debugBox = document.createElement("div");
       debugBox.id = "debugBox";
       document.body.appendChild(debugBox);
    }
}