$(function() {
    
    function loadModalWindow(activeMenuItem) {
        $("#wrapper object").css("visibility", "hidden");
        $("#overlay").css({ opacity: 0.7 }).show();
        $("#productModalWindow").animate({ width: "480px", marginLeft: "-260px" }, function() {
                $(this).animate({ height: "367px", marginTop: "-219px" }, function() {
                $(activeMenuItem).addClass("active").fadeIn();
                $("#productModalWindowClose").fadeIn();
                $("#productModaWindowNav").fadeIn();
                loadProductVideo();
            });
        });
    }

    function unloadModalWindow() {
        $("#productModalWindowClose").fadeOut();
        $("#productModaWindowNav").fadeOut();
        $("#productModalWindow > .active").removeClass("active").fadeOut();
        unloadProductVideo();
        $("#productModalWindow").animate({
            height: 0,
            marginTop: 0 
        }, function() {
            $(this).animate({
                width: 0,
                marginLeft: 0  
            }, function() {
                    $("#overlay").hide();
                    $("#wrapper object").css("visibility", "visible");
                    $(this).removeAttr("style");
                });
        });
    }

    function switchTab(activeMenuItem) {
        $("#productModalWindow > .active").removeClass("active").hide();
        $(activeMenuItem).addClass("active").show();
        if ( activeMenuItem == "#productVideoContainer" ) {
            loadProductVideo();
        } else {
            unloadProductVideo();
        }
    }
    
    function loadProductVideo() {
        var flashvars = {
           file: $("#productVideoURL").val(),
           autostart: true
        };
        var params = { allowFullScreen: true };
        var attributes = {
            id: "productVideo"
        };
        swfobject.embedSWF("/store/images/flv-player/player-licensed.swf", "productVideo", "480", "288", "9.0.0","expressInstall.swf", flashvars, params, attributes);
        
    }

    function unloadProductVideo() {
        $("#productVideo").replaceWith("<div id='productVideo'></div>");
    }    
    
    $("#productModalWindowClose").click(function() {
        unloadModalWindow();
    });
    
    $("#productShowcase a").click(function() {
        var thisElem = $(this);
        if ( thisElem.text() == "Zoom" ) {
            activateZoom();
            $("#productMoreViews").addClass("zoom");
        } else {
            deactivateZoom();
            $("#productMoreViews").removeClass("zoom");
        }
        if ( thisElem.attr("rel") ) {
            var activeMenuItem = thisElem.attr("rel");
            loadModalWindow(activeMenuItem);
            return false;
        }
    });
    
    $("#productModaWindowNav li a").click(function() {
        var thisElem = $(this);
        if ( thisElem.text() == "Zoom" ) {
            activateZoom();
            $("#productMoreViews").addClass("zoom");
        } else {
            deactivateZoom();
            $("#productMoreViews").removeClass("zoom");
        }
        if ( thisElem.attr("rel") ) {
            var activeMenuItem = thisElem.attr("rel");
            switchTab(activeMenuItem);
            return false;
        }
    });
    
    $("#productThumbnails a").click(function() {
        if ( $("#productMoreViewLargeIMG").is(":animated") ) {
            return false;
        } else {
            var thisElem = $(this);
            $("#productThumbnails a").removeClass("active");
            thisElem.addClass("active");
            $("#productMoreViewLarge").attr("rel", thisElem.attr("rel"));
            $("#productMoreViewLargeIMG").attr("src", thisElem.attr("href"));
            if ( $("#productMoreViews").hasClass("zoom") === true ) {
               activateZoom();
            }
            return false;
        }
    });
    
    /* Thumbnail Navigation */
    var $productThumbnails = $("#productThumbnails");
    var thumbnailWidth = 64;
    var thumbnailCount = $productThumbnails.children().length;
    if ( thumbnailCount > 5 ) {
        var thumbnailContainerWidth = thumbnailWidth * thumbnailCount;
        $("#productThumbnails").css("width", thumbnailContainerWidth + "px");
        var nextButton = $("<a href='#' id='thumbnailNext'>Next</a>");
        var prevButton = $("<a href='#' id='thumbnailPrev' class='disabled'>Previous</a>");

        var moreViewContainer = $("#productMoreViews");
        moreViewContainer.append(prevButton);
        moreViewContainer.append(nextButton);
        
        $("#thumbnailNext").click(function() {
            moveThumbnails("left");
            return false;
        });
        
        $("#thumbnailPrev").click(function() {
            moveThumbnails("right");
            return false;
        });      
        
        function moveThumbnails(direction) {
            var $productThumbnails = $("#productThumbnails");
            if ( $productThumbnails.is(":animated") === false ) {
                var currentXPosition = $productThumbnails.position().left;
                if ( direction == "left" ) {
                    var xpos = thumbnailWidth - thumbnailWidth - thumbnailWidth + currentXPosition;
                } else if ( direction == "right" ) {
                    var xpos = thumbnailWidth + currentXPosition;
                }
                if ( currentXPosition == 0 && direction == "right" ) {
                    //Don't know why I can't say the reverse...
                } else if ( thumbnailContainerWidth + currentXPosition <= 320 && direction == "left" ) {
                   //Doing the same to be safe...
                } else {
                    $("#productThumbnails").animate({
                        left: xpos
                    }, function() {
                        if ( $productThumbnails.position().left == 0 ) {
                            $("#thumbnailPrev").addClass("disabled");
                        } else {
                            $("#thumbnailPrev").removeClass("disabled");
                        }
                        if ( thumbnailContainerWidth + $productThumbnails.position().left <= 320 ) {
                            $("#thumbnailNext").addClass("disabled");
                        } else {
                            $("#thumbnailNext").removeClass("disabled");
                        }
                    });                
                }
            }
        }
        
    }
    
    /* Zooms */
    var $zoomPreview = $("#productMoreViewLarge");
    
    function activateZoom() {
        $("#zoomInstruct").show();
        var $zoomImage = $zoomPreview.attr("rel");
        if ($("#zoomLens").length < 1) {
            $zoomPreview.append("<div id='zoomLens'></div>");
        }
        var $zoomLens = $("#zoomLens");
        
        if ( $zoomLens.children().length > 0 ) {
            $zoomLens.children().remove();
        }
        
        $("<img />").attr("src", $zoomImage).load(function() {
            $zoomLens.append( $(this) );
        });

        $zoomPreview.bind("mouseover", function() {
            $zoomLens.show();
        });
        
        $zoomPreview.bind("mousemove", function(e) {
            var thisElem = $(this);
            var $zoomLensImage = $zoomLens.children("img");
            var thisImage = thisElem.children("img");
            var thisImageWidth = thisImage.width();
            var thisImageHeight = thisImage.height();
            var zoomImageWidth = $zoomLensImage.width();
            var zoomImageHeight = $zoomLensImage.height();
            var widthDivide = zoomImageWidth / thisImageWidth;
            var heightDivide = zoomImageWidth / thisImageWidth;
            var offset = thisElem.offset();
            var relativeX = e.pageX - offset.left;
            var relativeY = e.pageY - offset.top;
            var imageOffsetX = relativeX * widthDivide - 100;
            var imageOffsetY = relativeY * heightDivide - 100;
            var imageOffsetXOffset = imageOffsetX - imageOffsetX - imageOffsetX;
            var imageOffsetYOffset = imageOffsetY - imageOffsetY - imageOffsetY;
            
            $zoomLens.css({ top: relativeY, left: relativeX });
            $zoomLensImage.css({ top: imageOffsetYOffset, left: imageOffsetXOffset });
            
        });
        
        $zoomPreview.bind("mouseout", function() {
            $zoomLens.hide();
        });     
          
    }
    
    function deactivateZoom() {
        $("#zoomInstruct").hide();
        $zoomPreview.unbind("mouseover");
        $zoomPreview.unbind("mousemove");
        $zoomPreview.unbind("mouseout");     
    }      
    
    $("#productAltImagesRotator").innerfade({
        speed: 1000,
        timeout: 3000,
        containerheight: "171px"
    }).show().append("<li id='productAltImagesRotatorLink'><a href='#'><img src='/store/images/new-design-09/see-more-photos.jpg' alt='See More Photos' /></a></li>");    

    $("#productAltImagesRotator").click(function() {
        var thisElem = $(this);
        var activeMenuItem = thisElem.attr("rel");
        loadModalWindow(activeMenuItem);
        return false;
    });
        
    $("#currencyConverter").click(function() {
        var usdRate = 1.63972;
        var eurRate = 1.16289;
        $("#productVariations .price").each(function(i) {
            var thisElem = $(this);
            var gbpPrice = $.trim(thisElem.text());
        });
    });
    
    /* iPoints */
    $(".iPointsEarnings").hover(function() {
        $(this).parents("fieldset").css("z-index", 10).find(".iPointsExplainBox").show();
    }, function() {
        $(this).parents("fieldset").removeAttr("style").find(".iPointsExplainBox").hide();
    });  
    
    /* Email Me When Back In Stock 
    
    var $productVariations = $("#productVariations").find(".productVariationForm");
    
    for ( i=0; i < $productVariations.length; i++ ) {
        var $this = $productVariations.eq(i);
        var productCode = $this.find("input[name=productCode]").val();
        checkProductPO(productCode);
    }
    
    
    function checkProductPO(productCode) {
        var hasLivePO;
        $.ajax({
            type: "POST",
            beforeSend: function() {},
            url: "/myaccount/control/hasLivePO",
            data: "productId=" + productCode,
            success: function(data) {
                $("#productShowcase").data(productCode, data);
                showEmailWhenInStockLink(productCode);
            },
            complete: function() {}
        });
    }
    
    function showEmailWhenInStockLink(productCode) {
        if ( $("#productShowcase").data(productCode).indexOf("true") != -1 ) {
            var productCodeID = "#" + productCode;
            $(productCodeID).find(".emailMeWhenInStock").parent().removeClass("hidden");
        }
    }
    
    $(".emailMeWhenInStock").live("click", function() {
        var productCode = $(this).parents("fieldset").find("input[name=productCode]").val();
        setUpEmailMeForm(productCode);
        return false;
    });
    
    $("#emailBackCloseBtn").click(function() {
        resetEmailMeForm();
        return false;
    });
    
    function setUpEmailMeForm(productCode) {
        $("#emailBackSubmitForm").find("input[name=productId]").val(productCode);
        $("#emailBackSubmitForm").fadeIn();
    }
    
    function resetEmailMeForm() {
        $("#emailBackSubmitForm").find("input[name=productId]").val("");
        $("#emailBackSubmitForm").fadeOut();
    }
    
    $("#emailBackSubmitForm").submit(function() {
        var $this = $(this);
        $.ajax({
            type: $this.attr("method"),
            url: $this.attr("action"),
            data: $this.serialize(),
            beforeSend: function() {
                $("#emailBackPhase1").hide();
                $("#emailBackPhase2").show();
            },
            success: function() {
                $("#emailBackPhase2").hide();
                $("#emailBackPhase3").show();           
            }
        });
        return false;
    });
    
    */
    $("#productReviewLink").bind("click", function() {
        var link = $("#BVRRRatingSummaryNoReviewsWriteImageLinkID").find("a:first").attr("href");
        $(this).attr("href", link);
    });       
    $("#BVRRRatingSummaryNoReviewsWriteImageLinkID").find("a").attr("href");
    
});