﻿function InitializeHomeWidget(url) {
    $.ajax({
        url: url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            InitializeHomeWidget_Internal(data);
        }
    });
}

function InitializeHomeWidget_Internal(data) {
    if (data.success == true)
        data = data.data;
    else {
        data = null;
    }

    $(document).ready(function() {
        var slideshowDelay = 5000;
        var slideshowTimeoutId = 0;
        var currentChallengeIndex = parseInt($.cookie('sess_widgetCurrentChallengeIndex'));
        if (isNaN(currentChallengeIndex)) { currentChallengeIndex = 0; }
        var currentThumbnailIndex = 0;

        var $challengeWidget = $("#cw");
        var $challengeContainer = $("#cwChallengeContainer");
        var $linkElement = $challengeContainer.find("#cwChallengeLink");
        var $thumbnailContainer = $challengeContainer.find("#cwThumbnailContainer");
        var $thumbnailElement = $challengeContainer.find("#cwThumbnail");
        var $noThumbnailElement = $challengeContainer.find("#cwNoThumbnail");
        var $titleElement = $challengeContainer.find("#cwTitle");
        var $transitionDiv;

        //handle empty challenges (unlikely to happen though)
        if ((data == null) || (data.length == 0)) {
            $("#haveChallenge").css('display', 'none');
            $("#noChallenge").css('display', 'block');
        } else {
            $("#prevChallenge").bind("click", function() {
                ChangeEntry((currentChallengeIndex - 1) % (data.length - 1)); //TODO: not working
            });

            $("#nextChallenge").bind("click", function() {
                ChangeEntry((currentChallengeIndex + 1) % (data.length));
            });

            $challengeContainer.bind("mouseenter", function() {
                StopSlideshow();
            }).bind("mouseleave", function() {
                StartSlideshow();
            });

            function StartSlideshow() {
                if (slideshowTimeoutId == 0) //prevent duplicate schedule
                    ScheduleNextSlideshowChange();
            }

            function StopSlideshow() {
                window.clearTimeout(slideshowTimeoutId);
                slideshowTimeoutId = 0;
            }

            function ScheduleNextSlideshowChange() { slideshowTimeoutId = window.setTimeout(DisplayNext, slideshowDelay); }

            function DisplayNext() {
                var newChallengeIndex = (currentChallengeIndex + 1) % (data.length);
                ChangeEntry(newChallengeIndex);

                $.cookie('sess_widgetCurrentChallengeIndex', newChallengeIndex);
                ScheduleNextSlideshowChange();
            }

            function ChangeEntry(newChallengeIndex) {
                var newThumbnailIndex = Math.round(Math.random() * (data[newChallengeIndex]["Thumbnails"].length - 1));

                var prevThumbnail = data[currentChallengeIndex]["Thumbnails"][currentThumbnailIndex];
                if (prevThumbnail == null) prevThumbnail = { "ImageURL": "", "Height": 120, "Width": 120 };
                var activeThumbnail = data[newChallengeIndex]["Thumbnails"][newThumbnailIndex];
                if (activeThumbnail == null) activeThumbnail = { "ImageURL": "", "Height": 120, "Width": 120 };

                if ($transitionDiv) {
                    $transitionDiv.remove();
                }

                $transitionDiv = $("<div/>").
                        addClass("animationBackground").
                        css("overflow", "hidden").
                        css("margin-top", (70 - (prevThumbnail.Height / 2)) + "px").
                        css("width", prevThumbnail.Width + "px").
                        css("height", prevThumbnail.Height + "px");

                // new challenge does not have thumbnail
                if (data[newChallengeIndex]["Thumbnails"].length == 0) {
                    $thumbnailElement.css('display', 'none');
                    $noThumbnailElement.hide();
                } else {
                    $thumbnailElement.attr("src", activeThumbnail.ImageURL).hide();
                    $noThumbnailElement.hide();
                }

                $thumbnailContainer.append($transitionDiv);

                var animParams = {
                    marginTop: (70 - (activeThumbnail.Height / 2)) + "px",
                    width: activeThumbnail.Width + "px",
                    height: activeThumbnail.Height + "px"
                };

                $transitionDiv.animate(animParams, "normal", "linear", animationDone);

                function animationDone() {
                    $transitionDiv.remove();

                    // new challenge does not have thumbnail
                    if (data[newChallengeIndex]["Thumbnails"].length == 0) {
                        $thumbnailElement.css('display', 'none');
                        $noThumbnailElement.fadeIn();
                    } else {
                        $thumbnailElement.
                            css("margin-top", (70 - (activeThumbnail.Height / 2)) + "px").
                            css("width", activeThumbnail.Width + "px").
                            css("height", activeThumbnail.Height + "px").
                            fadeIn();
                        $noThumbnailElement.css('display', 'none');
                    }
                }

                //display data
                // option 1: display challenge data
                //// $linkElement.attr('href', data[newChallengeIndex].URL);
                //// $titleElement.text(data[newChallengeIndex].Title);
                // option 2: display entry data
                //$linkElement.attr('href', activeThumbnail.EntryURL);
                $linkElement.click(function() { window.location = (activeThumbnail.EntryURL + '&widget=1') });
                $titleElement.text(activeThumbnail.Title);

                currentChallengeIndex = newChallengeIndex;
                currentThumbnailIndex = newThumbnailIndex;
            }

            ChangeEntry(currentChallengeIndex);
            $challengeWidget.css('display', 'block');

            //start animation
            StartSlideshow();
        }
    });
}

function InitializeForumWidget(boxid, friendlyID, server) {
    var url = server + '/challenges/endpoints/challengesdata.ashx?id=' + friendlyID;
    $.ajax({
        url: url,
        type: "GET",
        dataType: "json",
        success: function(data) {
            InitializeForumWidgetInternal(boxid, data);
        }
    });
}

function InitializeForumWidgetInternal(boxid, data) {
    $(document).ready(function() {
        var slideshowDelay = 20000;
        var slideshowTimeoutId = 0;
        var currentChallengeIndex = parseInt($.cookie('sess_widgetCurrentChallengeIndex'));
        if (isNaN(currentChallengeIndex)) { currentChallengeIndex = 0; }

        var $challengeWidget = $("#" + boxid);
        var $miniContentContainer = $challengeWidget.find('#wbMiniContent');
        var $contentContainer = $challengeWidget.find('#wbContent');
        var $nocontentContainer = $challengeWidget.find('#wbNocontent');
        var $loadingContainer = $challengeWidget.find('#wbLoading');
        var $miniLoadingContainer = $challengeWidget.find('#wbLoadingMini');

        var $challengeTitleElement = $contentContainer.find("#challengeTitle");
        var $challengeLinkElement = $contentContainer.find("#challengeLink");
        var $challengeStatusElement = $contentContainer.find("#challengeStatus");

        var $challengeTitleMiniElement = $miniContentContainer.find("#challengeTitleMini");
        var $challengeLinkMiniElement = $miniContentContainer.find("#challengeLinkMini");
        var $challengeStatusMiniElement = $miniContentContainer.find("#challengeStatusMini");

        var $entryTitleElement = $contentContainer.find("#entryTitle");
        var $entryLinkElement = $contentContainer.find("#entryLink");
        var $entryStatusElement = $contentContainer.find("#entryStatus");

        var $openMaxiWidgetElement = $miniContentContainer.find("#openMaxiWidget");
        var $openMiniWidgetElement = $contentContainer.find("#openMiniWidget");

        var $thumbnailElement = $contentContainer.find("#activeThumbnail");
        var $otherChallengeThumbnailsElement = $contentContainer.find("#otherChallengeThumbnails");

        //handle empty js file (if nothing to display / not found)
        if ((data == null) || (data.length == 0)) {
            $loadingContainer.hide();
            $miniLoadingContainer.hide();
            $nocontentContainer.show();
        } else {
            if ($.cookie('sess_miniWidget') == 'true') {
                $miniLoadingContainer.hide();
                $miniContentContainer.show();
            } else {
                $loadingContainer.hide();
                $contentContainer.show();
            }

            $contentContainer.bind("mouseenter", function() {
                StopSlideshow();
            }).bind("mouseleave", function() {
                StartSlideshow();
            });

            function StartSlideshow() {
                if (slideshowTimeoutId == 0) //prevent duplicate schedule
                    ScheduleNextSlideshowChange();
            }

            function StopSlideshow() {
                window.clearTimeout(slideshowTimeoutId);
                slideshowTimeoutId = 0;
            }

            function ScheduleNextSlideshowChange() { slideshowTimeoutId = window.setTimeout(DisplayNext, slideshowDelay); }

            function DisplayNext() {
                var newChallengeIndex = (currentChallengeIndex + 1) % (data.length);
                ChangeChallenge(newChallengeIndex);

                $.cookie('sess_widgetCurrentChallengeIndex', newChallengeIndex);
                ScheduleNextSlideshowChange();
            }

            function ChangeChallenge(newChallengeIndex) {
                var currentChallenge = data[newChallengeIndex];

                var entryIndex = 0; // hardcoded since the JSON generator only generate one entry
                var currentEntry = currentChallenge.Entries[entryIndex];

                var currentThumbnail = currentEntry.Thumbnails[0];
                if (currentThumbnail == null) currentThumbnail = { "ImageURL": "", "Height": 120, "Width": 120 };

                // step 1: display challenge data
                $challengeTitleElement.text(currentChallenge.Title);
                $challengeLinkElement.attr('href', currentChallenge.URL + '&widget=1');
                $challengeStatusElement.html(currentChallenge.StatusText);

                // step 1b: display mini challenge data
                $challengeTitleMiniElement.text(currentChallenge.Title);
                $challengeLinkMiniElement.attr('href', currentChallenge.URL + '&widget=1');
                $challengeStatusMiniElement.html(currentChallenge.StatusText);

                if ($.cookie('sess_miniWidget') != 'true') {
                    // step 2: display entry data
                    $entryTitleElement.text(currentEntry.Title);
                    $entryLinkElement.attr('href', currentEntry.URL + '&widget=1');
                    $entryStatusElement.text(currentEntry.StatusText);

                    // step 3: display thumbnail
                    $thumbnailElement.
                        attr("src", currentThumbnail.ImageURL).
                        click(function() { window.location = (currentChallenge.URL + '&widget=1') }).
                        hide();
                    $thumbnailElement.
                        css("margin-top", (60 - (currentThumbnail.Height / 2)) + "px").
                        css("width", currentThumbnail.Width + "px").
                        css("height", currentThumbnail.Height + "px").
                        show();
                }

                currentChallengeIndex = newChallengeIndex;
            }

            function BindChallenges() {
                $openMaxiWidgetElement.click(function() {
                    $miniContentContainer.hide();
                    $contentContainer.show();
                    $.cookie('sess_miniWidget', 'false');
                });

                $openMiniWidgetElement.click(function() {
                    $miniContentContainer.show();
                    $contentContainer.hide();
                    $.cookie('sess_miniWidget', 'true');
                });

                for (var i = 0; i < data.length; i++) {
                    $otherChallengeThumbnailsElement.append(
                        GenerateChallengeThumbnail(i)
                    );

                    if (i == 7) {
                        $otherChallengeThumbnailsElement.append(
                            $("<div style='clear: both'></div>")
                        );
                        return;
                    }
                }
            }

            function GenerateChallengeThumbnail(index) {
                var currentChallenge = data[index];

                var entryIndex = 0; // hardcoded since the JSON generator only generate one entry
                var currentEntry = currentChallenge.Entries[entryIndex];

                var currentThumbnail = currentEntry.Thumbnails[1];
                if (currentThumbnail == null) currentThumbnail = { "ImageURL": "", "Height": 40, "Width": 40 };

                return $("<img class='challengeThumbnail' />").attr('src', currentThumbnail.ImageURL)
                            .hover(function() { $(this).css('border-color', '#999'); }, function() { $(this).css('border-color', '#666'); })
                            .mouseover(function() { ChangeChallenge(index); })
                            .click(function() { window.location = currentChallenge.URL; });
            }

            // load initial value
            ChangeChallenge(currentChallengeIndex);
            BindChallenges();

            //start animation
            StartSlideshow();
        }
    });
}

function InitializeSquareForumWidget(friendlyID) {
    var url = 'http://www.dpreview.com/inc/generated/challenges/' + friendlyID + '.js';
    $.ajax({
        url: url,
        type: "GET",
        dataType: "json",
        success: function(data) {
        InitializeSquareForumWidget_Internal(data);
        }
    });
}

function InitializeSquareForumWidget_Internal(data) {
    $(document).ready(function() {
        var slideshowDelay = 5000;
        var slideshowTimeoutId = 0;
        var currentChallengeIndex = parseInt($.cookie('sess_widgetCurrentChallengeIndex'));
        if (isNaN(currentChallengeIndex)) { currentChallengeIndex = 0; }

        var $challengeWidget = $("#cw");
        var $contentContainer = $challengeWidget.find('.content');
        var $nocontentContainer = $challengeWidget.find('.nocontent');
        var $loadingContainer = $challengeWidget.find('.loading');

        var $thumbnailElement = $contentContainer.find("#cwThumbnail");
        var $noThumbnailElement = $contentContainer.find("#cwNoThumbnail");

        var $challengeTitleElement = $contentContainer.find("#cwChallengeTitle");
        var $challengeLinkElement = $contentContainer.find("#cwChallengeLink");
        var $challengeLinkActionElement = $contentContainer.find("#cwChallengeLinkAction");
        var $entryTitleElement = $contentContainer.find("#cwEntryTitle");
        var $entryLinkElement = $contentContainer.find("#cwEntryLink");

        var $challengePhaseL1Element = $contentContainer.find("#cwPhaseLine1");
        var $challengePhaseL2Element = $contentContainer.find("#cwPhaseLine2");
        var $challengeInfoElement = $contentContainer.find("#cwChallengeInfo");

        //handle empty js file (if nothing to display / not found)
        if ((data == null) || (data.length == 0)) {
            $loadingContainer.css('display', 'none');
            $nocontentContainer.css('display', 'block');
        } else {
            $loadingContainer.css('display', 'none');
            $contentContainer.css('display', 'block');

            $contentContainer.bind("mouseenter", function() {
                StopSlideshow();
            }).bind("mouseleave", function() {
                StartSlideshow();
            });

            function StartSlideshow() {
                if (slideshowTimeoutId == 0) //prevent duplicate schedule
                    ScheduleNextSlideshowChange();
            }

            function StopSlideshow() {
                window.clearTimeout(slideshowTimeoutId);
                slideshowTimeoutId = 0;
            }

            function ScheduleNextSlideshowChange() { slideshowTimeoutId = window.setTimeout(DisplayNext, slideshowDelay); }

            function DisplayNext() {
                var newChallengeIndex = (currentChallengeIndex + 1) % (data.length);
                ChangeEntry(newChallengeIndex);

                $.cookie('sess_widgetCurrentChallengeIndex', newChallengeIndex);
                ScheduleNextSlideshowChange();
            }

            function ChangeEntry(newChallengeIndex) {
                var currentChallenge = data[newChallengeIndex];
                var currentThumbnailIndex = Math.round(Math.random() * (data[newChallengeIndex].Thumbnails.length - 1));
                var currentThumbnail = currentChallenge.Thumbnails[currentThumbnailIndex];
                if (currentThumbnail == null) currentThumbnail = { "ImageURL": "", "Height": 120, "Width": 120 };

                // new challenge does not have thumbnail
                if (currentChallenge.Thumbnails.length == 0) {
                    $thumbnailElement.hide();
                    $noThumbnailElement.show();
                } else {
                    $thumbnailElement.attr("src", currentThumbnail.ImageURL).hide();
                    $noThumbnailElement.show();
                }

                // new challenge does not have thumbnail
                if (currentChallenge.Thumbnails.length == 0) {
                    $thumbnailElement.css('display', 'none');
                    $noThumbnailElement.fadeIn(1200);
                } else {
                    $thumbnailElement.
                        css("margin-top", (120 - (currentThumbnail.Height / 2)) + "px").
                        css("width", currentThumbnail.Width + "px").
                        css("height", currentThumbnail.Height + "px").
                        fadeIn();
                    $noThumbnailElement.css('display', 'none');
                }

                // step 1: display challenge data
                $challengeTitleElement.text(currentChallenge.Title);
                $challengeLinkElement.click(function() { window.location = currentChallenge.URL; });

                // step 2: display entry data
                $entryTitleElement.text(currentThumbnail.Title);
                $entryLinkElement.attr('href', currentThumbnail.EntryURL + '&widget=1');

                // step 3: switch challenge status
                switch (currentChallenge.Status) {
                    case 4: // ChallengeStatus.OpenForSubmissions
                        $challengeLinkActionElement.text('Enter');
                        break;
                    case 6: // ChallengeStatus.JudgingVoting
                        $challengeLinkActionElement.text('Vote');
                        break;
                    case 7: // ChallengeStatus.Exhibition
                        $challengeLinkActionElement.text('View');
                        break;
                }

                var phaseInfoL1 = currentChallenge.StatusText.split('|', 2)[0];
                var phaseInfoL2 = currentChallenge.StatusText.split('|', 2)[1];

                $challengePhaseL1Element.text(phaseInfoL1);
                $challengePhaseL2Element.text(phaseInfoL2);
                $challengeInfoElement.html(currentChallenge.ChallengeInfoText);

                currentChallengeIndex = newChallengeIndex;
            }

            ChangeEntry(currentChallengeIndex);
            $challengeWidget.css('display', 'block');

            //start animation
            StartSlideshow();
        }
    });
}