﻿function Challenge(challengeId, clientViewId, loggedIn, loginUrl, justSubmittedEntryId, showTooltips, enableLightbox, enableCommenting, entries)
{

    var popupManager = new EntryPopup();
    var lightbox = enableLightbox ? new Lightbox(challengeId) : null;
    
    $(document).ready(function()
    {
        initEntries();
    });

    function initEntries()
    {

        var viewModeHandler = getViewHandler(clientViewId);

        for (var i = 0; i < entries.length; i++)
        {

            var entry = entries[i];

            var $cont = $("#" + entry.entryContainerId);
            var $img = $cont.find("img.entry, div.entryPlaceholder");
            var $tools = $cont.find("div.entryInfo");

            if (justSubmittedEntryId && justSubmittedEntryId == entry.entryId)
            {
                showJustSubmitted($tools);
            }
            
            if (enableLightbox && !entry.placeholder)
            {
                addLightboxLink(entry.entryId, $cont, $img);
            }
            
            if (enableCommenting)
            {
                addCreateCommentLink(entry.entryId, $cont, $img);
            }
            
            hookEntryImageHover(entry.entryId, $cont, $img);

            if (viewModeHandler)
            {
                viewModeHandler.init(
		            $tools.get(0),
		            challengeId,
		            entry.entryId,
		            entry.viewSpecificInfo,
		            loggedIn,
		            askForLogin,
		            new EntryMessage($img.get(0)),
		            updateNumberOfVotes);
            }

        }

    }

    function getViewHandler(clientViewId)
    {
        switch (clientViewId)
        {
            case "voting": return new VotingViewHandler();
            default: return null;
        }
    }

    function showJustSubmitted($tools)
    {
        $("<div/>").
            addClass("justSubmitted").
            append($("<table/>").
                append($("<tr/>").
                    append($("<td/>").addClass("icon")).
                    append($("<td/>").addClass("text").text("Just submitted!")))).
            appendTo($tools);
    }

    function hookEntryImageHover(entryId, $cont, $img)
    {
    
        var $zoomIcon = $cont.find(".imgIcon");
        var $imageAndZoomIcon = $img.add($zoomIcon);
        
        $imageAndZoomIcon.hover(
		    function(event)
		    {
		        $zoomIcon.show();
		        if (showTooltips) popupManager.show(entryId);
		    },
		    function()
		    {
		        $zoomIcon.hide();
		        if (showTooltips) popupManager.hide();
		    });
		    
        if (showTooltips) 
        {		    
            $imageAndZoomIcon.mousemove(function(event)
            {
                popupManager.positionPopup(event);
            });
        }

    }
    
    function addLightboxLink(entryId, $cont, $img)
    {
    
        function draggableHelper(entryId)
        {
            return $("<img/>").
                attr("src", createEntryImageSrc(entryId, "micro")).
                attr("width", "40").
                attr("height", "40").
                attr("border", "0").
                attr("alt", "Add to lightbox").
                css("border", "1px solid White").
                data("entryId", entryId).
                appendTo(document.body).
                get(0);
        }
    
        $cont.find("div.imgInternalFrame").
            data("entryId", entryId).
            draggable({
                zIndex: 1,
                helper: function() { return draggableHelper(entryId) },
                cursorAt: {top: 20, left: 20} });
    
        $("<div/>").
            addClass("imgIcon").
            addClass("addToLightboxIcon").
            attr("title", "Add image to lightbox.").
            click(function() { lightbox.addEntryToLightbox(entryId, $img.get(0)) }).
            appendTo($cont.find("div.imgInternalFrame"));

    }
    
    function addCreateCommentLink(entryId, $cont, $img)
    {
    
        var entryLink = $cont.
            find("div.imgInternalFrame > a").
            attr("href");
    
        $("<div/>").
            addClass("imgIcon").
            addClass("addCommentIcon").
            attr("title", "Comment on this image.").
            click(function() { location.href = entryLink + "#comment"; }).
            appendTo($cont.find("div.imgInternalFrame"));
    
    }

    function askForLogin()
    {
        new FullScreenMessage(
	        "<div class=\"messageTitle\">You'll need to login or register to vote.</div>" +
	        "<div class=\"messageText\">" +
	        "You are not logged in at the moment. Voting requires a dpreview.com account. " +
	        "Please <a href=\"" + loginUrl + "\" rel=\"nofollow\">login</a> or create a " +
	        "<a href=\"http://www.dpreview.com/forums/register.asp\">new account</a>." +
	        "</div>");
    }

    function updateNumberOfVotes(votesCount, votesCountFormatted)
    {
        $("#challengeSummaryVotesCount").text(votesCountFormatted);
    }

}

function VotingViewHandler()
{

    this.init = function(
        voteContainerElement,
        challengeId,
        entryId,
        viewSpecificInfo,
        loggedIn,
        askForLoginCallback,
        messager,
        updateNumberOfVotesCallback)
    {

        // create widget
        var votingWidget = new VotingStars(
            voteContainerElement,
            challengeId,
            entryId,
            loggedIn,
            askForLoginCallback,
            messager,
            updateNumberOfVotesCallback);

        // init and set votes
        votingWidget.setMagnitude(viewSpecificInfo.voted, viewSpecificInfo.magnitude);

    }

}

function EntryMessage(imgEntryElement)
{

    var $message = null;

    // public
    this.hideCurrent = function()
    {
        if ($message)
        {
            $message.fadeOut("normal", remove);
        }
    }

    // public
    this.displayMessage = function(message)
    {

        if ($message)
        {
            $message.stop().remove();
        }

        var $img = $(imgEntryElement);
        var width = $img.attr("width");
        var height = $img.attr("height");

        $message = $("<div/>").
	        addClass("message").
	        css("width", width + "px").
	        css("height", height + "px").
	        append($("<div/>").addClass("messageIcon").addClass("messageIconSuccess")).
	        append($("<div/>").addClass("messageText").text(message)).
	        appendTo($img.parent());

        $message.queue(sleep);

    }

    // private
    function sleep()
    {
        var $thisMessage = $(this);
        window.setTimeout(function() { $thisMessage.dequeue(); }, 500);
    }

    // private
    function remove()
    {
        $(this).remove();
    }

}

function EntryPopup()
{

    var $currentPopup;
    var cachedEntryInfo = [];

    // public
    this.show = function(entryId)
    {
    
        hidePopup();

        // try cache first
        var entry = cachedEntryInfo[entryId];
        
        // from cache
        if (entry)
        {

            $currentPopup = $("<div/>").
                addClass("entryPopupInfo").
                appendTo("body");
            
            populateAndDisplay(entry);
            
        }
        
        // loading from server
        else
        {
        
            $currentPopup = $("<div/>").
                addClass("entryPopupInfo").
                appendTo("body").
                append($("<div/>").addClass("loading").text("Loading ..."));

            var request = {
                url: "EndPoints/EntryPopupInfo.ashx",
                type: "GET",
                data: { ID: entryId },
                dataType: "json",
                success: infoLoaded,
                error: infoLoadError };

            $.ajax(request);
        
        }

    }

    // public
    this.positionPopup = function(event)
    {
        if ($currentPopup)
        {
            $currentPopup.
                css("left", (event.pageX + 20) + "px").
                css("top", (event.pageY + 20) + "px");
        }
    }

    // public
    this.hide = function()
    {
        hidePopup();
    }

    // private
    function hidePopup()
    {
        if ($currentPopup)
        {
            $currentPopup.remove();
        }
    }

    // private
    function infoLoaded(entry)
    {
        cachedEntryInfo[entry.entryId] = entry;
        populateAndDisplay(entry);
    }
    
    // private
    function infoLoadError()
    {
        $currentPopup.empty().append($("<div/>").
            addClass("error").
            text("Error while loading data."));
    }

    // private
    function createInfoTitleDOM(title)
    {
        return $("<div/>").addClass("title").text(title);
    }
    
    // private
    function createInfoLineDOM(label, value)
    {
        return $("<div/>").addClass("info").
            append($("<span/>").addClass("label").text(label + ":")).
            append(" ").
            append($("<span/>").addClass("value").text(value));
    }

    // private
    function populateAndDisplay(entry)
    {
        $currentPopup.empty().
            append(createInfoTitleDOM(entry.title)).
            append(createInfoLineDOM("By", entry.owner)).
            append(createInfoLineDOM("Taken", entry.captureDate)).
            append(createInfoLineDOM("Sumitted", entry.submissionDate)).
            append(createInfoLineDOM("Camera", entry.camera)).
            append(createInfoLineDOM("Lens", entry.lensDescription)).
            append(createInfoLineDOM("Focal length", entry.focalLength)).
            append(createInfoLineDOM("Shutter speed", entry.shutterspeed)).
            append(createInfoLineDOM("Aperture", entry.fNumber)).
            append(createInfoLineDOM("ISO", entry.ISO));
    }

}

// IE6 hover workaround
$(document).ready(function()
{

    $("#viewModeMenu").mouseover(function()
    {
        $(this).addClass("viewModeMenuHover");
    }).mouseout(function()
    {
        $(this).removeClass("viewModeMenuHover");
    });

    $("#pageSelector").mouseover(function()
    {
        $(this).addClass("pageSelectorHover");
    }).mouseout(function()
    {
        $(this).removeClass("pageSelectorHover");
    });

    $("#rowSelector").mouseover(function()
    {
        $(this).addClass("rowsSelectorHover");
    }).mouseout(function()
    {
        $(this).removeClass("rowsSelectorHover");
    });

});
