
$(document).ready( function () {
    var $loading    = $('<div id="loading">Loading...</div>').prependTo('#potw-div');

    var $activePOTW = null;

    var $potyLink   = $(".poty-results-link a").click( function(event) {

        if ( $activePOTW ) {
            $activePOTW.hide();
            $activePOTW     = null;
        }

        $("#poty-results").fadeIn();

        event.preventDefault();
    });

    $("#potw-collection-thumbs a").click( function (event) {
        // Not efficient, but hide POTY Voting Results just in case it's visible
        $("#poty-results").hide();

        // Hide the current and show the Loading...
        if ( $activePOTW ) {
            $activePOTW.hide();
            $activePOTW     = null;
        }

        $loading.show();

        // Find the new Photo to show and see if it's photo is already loaded
        var $thumb          = this;
        var divId           = $($thumb).children(".potw-week-id").text();
        var $potwDiv        = $("#" + divId);
        var $potwPhotoDiv   = $potwDiv.children(".photo-div");
        var $potwImg        = $potwPhotoDiv.children("img");
        var potwTitle       = $potwDiv.children(".potw-title").text();

        $activePOTW = $potwDiv;

        var showPOTW = function () {
            $loading.hide();
            $activePOTW.fadeIn();
        };

        // If image not already created and loaded, create it and add to the
        // div.
        if ( $potwImg.length == 0 ) {
            $potwImg    = $("<img/>").attr( {alt: potwTitle, title: potwTitle} );
            $potwImg.prependTo($potwPhotoDiv);
            $potwImg.bind("load", showPOTW);
            $potwImg.attr("src", $($thumb).attr("href"));
        } else {
            showPOTW();
        }

        event.preventDefault();
    });

    $("#potw-collection-thumbs a").eq(0).trigger( "click" );

});


