$(document).ready(function () {

    popup =
		$("<div />")
		.css("css", 'z-index:5')
		.attr("id", 'thumbPopup')
		.css("position", "absolute")
		.appendTo("body").hide();

    $("#homepageSofas img.homeSofa").hover(setPopup)
		.mousemove(updatePopupPosition)
		.mouseout(hidePopup);

    function setPopup(event) {
        var fullImgURL = "/images/recliner-sofas/homepage/leather-recliner-sofa-" + $(this).attr('id') + ".jpg";
        
        //var $sections = $(this).attr('src').split("/");
        //var fullImgURL = '/images/' + $sections[$sections.length - 1];

        $(this).data("hovered", true);

        //Load full image in popup
        $("<img />")
			.bind("load", { thumbImage: this }, function (event) {
			    //Only display the larger image if the thumbnail is still being hovered
			    if ($(event.data.thumbImage).data("hovered") == true) {
			        $(popup).empty().append(this);
			        updatePopupPosition(event);
			        $(popup).show();
			    }
			    $(event.data.thumbImage).data("cached", true);
			})
			.attr("src", fullImgURL);

        //If no image has been loaded yet then place a loading message
        if ($(this).data("cached") != true) {
            $(popup).append($("<span style='padding: 5px;'><img src='/images/loading.gif' /></span>"));
            $(popup).show();
        }

        updatePopupPosition(event);
    }

    function updatePopupPosition(event) {
        var windowSize = getWindowSize();
        var popupSize = getPopupSize();
        if (windowSize.width + windowSize.scrollLeft < event.pageX + popupSize.width + 15) {
            $(popup).css("left", event.pageX - popupSize.width - 15);
        } else {
            $(popup).css("left", event.pageX + 15);
        }
        if (windowSize.height + windowSize.scrollTop < event.pageY + popupSize.height + 15) {
            $(popup).css("top", event.pageY - popupSize.height - 15);
        } else {
            $(popup).css("top", event.pageY + 15);
        }
    }

    function hidePopup(event) {
        $(this).data("hovered", false);
        $(popup).empty().hide();
    }

    function getWindowSize() {
        return {
            scrollLeft: $(window).scrollLeft(),
            scrollTop: $(window).scrollTop(),
            width: $(window).width(),
            height: $(window).height()
        };
    }

    function getPopupSize() {
        return {
            width: $(popup).width(),
            height: $(popup).height()
        };
    }
});