﻿// Featured article carousel variables
var curIdx = 0;
//var intervalID = 0;
//var secondsPerPage = 7;

// Assets paging control variables
var curPageItemsIdx = 1;

$(document).ready(function() {
    // Set Home button to "on"
    turnOnHomeButton();

    // Handle a custom event triggered by the segment list control when it registers a selection
    $("#topBar").bind("connectionsCenterSelected", connectionsCenterSelected);

    // Handle a custom event triggered by the sort by list control when it registers a selection
    $("#leftListTopBarDropDownContainer").bind("filterSelected", function() { showAssets(1); });

    // Check cookie for number of items displayed
    var numAssetsDisplayed = readCookie("an");
    if (numAssetsDisplayed == null) {
        numAssetsDisplayed = 5;
    }
    setNumAssetsDisplayed(parseInt(numAssetsDisplayed), true);
});

function setSort(type) {
    if (type != "date" && type != "popular") {
        type = "date";
    }
    createCookie("as", type, 365);
    showAssets(1);
}

function setNumAssetsDisplayed(numAssetsDisplayed, isInit) {
    // Get the old value for calculations
    var oldValueStr = readCookie("an");
    if (oldValueStr == null) {
        oldValueStr = "5";
    }
    var oldValue = parseInt(oldValueStr);
    if (isNaN(oldValue)) {
        oldValue = 5;
    }

    // Figure out the new items per page value
    numAssetsDisplayed = parseInt(numAssetsDisplayed);
    if (isNaN(numAssetsDisplayed) || (numAssetsDisplayed != 5 && numAssetsDisplayed != 10 && numAssetsDisplayed != 15)) {
        numAssetsDisplayed = 5;
    }
    createCookie("an", numAssetsDisplayed, 365);

    // Figure out what page the topmost event will be displayed on after the number of items
    // in each page of the list changes
    var topMostItemIdx = (curPageItemsIdx - 1) * oldValue;
    var newPageNo = (topMostItemIdx / numAssetsDisplayed) + 1; // Integer division will round down

    // Update the display
    $("#leftListItemContainer").removeClass("leftListItemContainer5").removeClass("leftListItemContainer10").removeClass("leftListItemContainer15").addClass("leftListItemContainer" + numAssetsDisplayed);
    $("#show5").removeClass("on");
    $("#show10").removeClass("on");
    $("#show15").removeClass("on");
    $("#show" + numAssetsDisplayed).addClass("on");

    if (!isInit) {
        showAssets(newPageNo, numAssetsDisplayed);
    }
}

function showNextAssetPage() {
    var totalNumPages = $("#leftListBottomBarPaginationContainer a").length - 1; // The -1 is to remove the NEXT link from the count
    var nextPage = (curPageItemsIdx % totalNumPages) + 1;
    showAssets(nextPage);
}

function showAssets(pageNo, numAssetsDisplayed) {
    curPageItemsIdx = pageNo;
    if (numAssetsDisplayed == null) {
        numAssetsDisplayed = readCookie("an");
    }
    if (numAssetsDisplayed == null) {
        numAssetsDisplayed = 5;
    }
    numAssetsDisplayed = parseInt(numAssetsDisplayed);
    if (isNaN(numAssetsDisplayed) || (numAssetsDisplayed != 5 && numAssetsDisplayed != 10 && numAssetsDisplayed != 15)) {
        numAssetsDisplayed = 5;
    }

    var sortType = readCookie("as");
    if (sortType == null || (sortType != "date" && sortType != "popular")) {
        sortType = "date";
    }

    $("#positionIndicatorContainer").fadeOut();
    $("#leftListBottomBarPaginationContainer").fadeOut();
    $("#leftListItems").fadeOut(function() {
        // Show transparent overlay
        $("#leftListItemOverlay").fadeIn("fast");

        // Load assets list content
        if ($(".currentSortBy").length > 0) {
            var id = $(".currentSortBy:first").attr("id");
            id = id.substring(0, id.length - 4);

            var url = "/ajaxcontent/AssetList.aspx?filter=" + id + "&n=" + numAssetsDisplayed + "&p=" + pageNo + "&sort=" + sortType + " #assetList";
            $("#leftListItems").load(url, function() {
                // Hide the bottom border of the last item
                $(".assetItem:last").addClass("lastAssetItem");

                $("#sortMostPopular").removeClass("on");
                $("#sortMostRecent").removeClass("on");

                if (sortType == "popular") {
                    $("#sortMostPopular").addClass("on");
                }
                else {
                    $("#sortMostRecent").addClass("on");
                }

                // Load the other parts of the page that were retrieved by the above AJAX call:
                // Position indicator (showing m-n of p)
                // Pagination container (1 2 3 NEXT >)
                $("#positionIndicatorContainer").html("").append($("#leftListItems #positionIndicator"));
                $("#leftListBottomBarPaginationContainer").html("").append($("#leftListItems #paginationContainer"));

                $("#leftListItemOverlay").fadeOut("fast");
                $("#leftListItems").fadeIn();
                $("#positionIndicatorContainer").fadeIn();
                $("#leftListBottomBarPaginationContainer").fadeIn();
                // Show a transparent GIF instead of the PNG for the NEXT button in IE6
                if ($.browser.msie && $.browser.version.substr(0, 1) == "6") {
                    $("#leftListBottomBarPaginationContainer img:last").attr("src", "/images/page_next.gif");
                }

            });
        }
        else {
            $("#leftListItems").html("&nbsp;");
            $("#leftListItemOverlay").fadeOut("fast");
        }
    });
}

function connectionsCenterSelected(event, id, fromClick, cb) {
//    if (intervalID > 0) {
//        clearInterval(intervalID);
//    }
// 
    // Fade out current content
    $("#floatingBoxHead span").fadeOut();
    $("#floatingBoxBodyContent").fadeOut();
    $("#floatingBoxLink").fadeOut();
    $("#rightSideTopBoxContent").fadeOut();
    $("#rightSideBottomBoxContent").fadeOut();
    $("#rightSideBottomBoxTopBar .rightSideBoxTitle:first").fadeOut();
    $("#pollBoxContent").fadeOut();
    $("#homeMainContentContainer").fadeOut(function() {
        // Show transparent overlays
        $("#mainContentOverlay").fadeIn("fast");
        $("#rightSideTopBoxOverlay").fadeIn("fast");
        $("#rightSideBottomBoxOverlay").fadeIn("fast");
        $("#pollBoxOverlay").fadeIn("fast");

        if (id != "unsegmented") {
            selectFilter(id + "Sort");
        }
        else {
            selectFilter("forSeniorExecutivesSort");
        }

        // Load connections center content
        var idx = ids.indexOf(id);
        var contentID = unsegmentedID;
        if (idx != -1) {
            contentID = contentIDs[idx];
        }

        $("#homeMainContentContainer").load("/ajaxcontent/HomeMainContent.aspx?id=" + contentID + " #homeMainContent", function() {
            // Load floating box content
            $("#floatingBoxContentHolder").load("/ajaxcontent/HomeFloatingBox.aspx?id=" + contentID + " #homeFloatingBox", function() {
                $("#mainContentOverlay").fadeOut("fast");
                initFloatingBox(function() { $("#homeMainContentContainer").fadeIn(); });
            });

            // Load featured event
            // Featured event ID is stored in hiddenFeaturedEventIDContainer's hidden input field
            var eventID = $("#hiddenFeaturedEventIDContainer input:first").val();
            if (eventID != null && !isNaN(parseInt(eventID))) {
                $("#rightSideTopBoxContent").load("/ajaxcontent/FeaturedEvent.aspx?id=" + eventID + " #featuredEventContainer", function() {
                    // Fade transparent overlay
                    $("#rightSideTopBoxOverlay").fadeOut("fast");
                    $("#rightSideTopBoxContent").fadeIn();
                    $("#rightSideTopBoxTopBar").fadeIn("fast");
                    $("#rightSideTopBox").fadeIn("fast");
                });
            }
            else {
                $("#rightSideTopBoxTopBar").fadeOut("fast");
                $("#rightSideTopBox").fadeOut("fast");
            }

            // Load featured blogger
            $("#rightSideBottomBoxContent").load("/ajaxcontent/FeaturedBlogger.aspx #featuredBloggerContainer", function() {
                // Move title up
                var title = $("#blogTitle").html().trim();
                //alert($("#rightSideBottomBoxTopBar .rightSideBoxTitle").length);
                $("#rightSideBottomBoxTopBar .rightSideBoxTitle:first").html(title);
                $("#blogTitle").empty();
                // Fade transparent overlay
                $("#rightSideBottomBoxOverlay").fadeOut("fast");
                $("#rightSideBottomBoxContent").fadeIn();
                $("#rightSideBottomBoxTopBar .rightSideBoxTitle:first").fadeIn();
            });

            // Load poll
            // Poll form ID is stored in hiddenPollIDContainer's hidden input field
            var pollID = $("#hiddenPollIDContainer input:first").val();
            if (pollID != null && !isNaN(parseInt(pollID))) {
                if (readCookie("pollComplete_" + pollID) != null) {
                    // Poll has been completed - show results
                    loadPollResults(pollID, function() {
                        $("#pollBoxOverlay").fadeOut("fast");
                        $("#pollBoxContent").fadeIn();
                    });
                }
                else {
                    // Poll has not been completed - show questions
                    $("#pollBoxContent").load("/ajaxcontent/Poll.aspx?id=" + pollID + " .pollQuestions:first", function() {
                        // Wire up button click events
                        $("#rblAnswers").attr("cellspacing", "0").attr("cellpadding", "0");
                        $("#btnSubmitPoll").click(function() {
                            if ($(".pollQuestions:first input:checked").length > 0) {
                                submitPoll(pollID);
                            }
                        });
                        // Fade transparent overlay
                        $("#pollBoxOverlay").fadeOut("fast");
                        $("#pollBoxContent").fadeIn();
                    });
                }
            }
            else {
                $("#pollContainer").fadeOut("fast");
            }
        });

        if (cb != null) { cb(); }
    });
}

function turnOnHomeButton() {
    $("#homeNavBtn").addClass("on");
}

function initFloatingBox(cb) {
    // Figure out if there are any pages here
    var pageCount = $(".floatingBoxContents").length;
    if (pageCount > 1) {
        // Set up pagination controls
        var pageLinks = new Array(pageCount);
        for (var i = 1; i <= pageCount; i++) {
            pageLinks[i - 1] = "<a id='floatingBoxPage_" + i + "' class='paginationLink' href='javascript:goToFloatingBoxPage(" + i + ");'>" + i + "</a>";
        }
        $("#floatingBoxPageLinks").html(pageLinks.join(""));
        $("#floatingBoxPageLinks").show();
        $("#floatingBoxPage_Next").show();
        // Show a transparent GIF instead of the PNG for IE6
        if ($.browser.msie && $.browser.version.substr(0, 1) == "6") {
            $("#floatingBoxPage_Next img").attr("src", "/images/page_next.gif");
        }
        $("#floatingBoxPause").show();
    }
    else {
        // If one or zero pages, hide the pagination controls
        $("#floatingBoxPageLinks").hide();
        $("#floatingBoxPage_Next").hide();
        $("#floatingBoxPause").hide();
    }

    if (pageCount > 0) {
        // Show the first page
        curIdx = 1;
        showFloatingBoxPage(cb);
//        if (pageCount > 1) {
//            intervalID = setInterval("autoShowFloatingBox()", secondsPerPage * 1000);
//        }
    }
    else {
        if (cb != null) { cb(); }
    }
}

//function toggleCarousel() {
//    if (intervalID != 0) {
//        clearInterval(intervalID);
//        intervalID = 0;
//        // Change icon to "play"
//        $("#floatingBoxPause").fadeOut("fast", function() {
//            $(this).css("background-image", "url(/images/play.png)").text("RESUME").fadeIn("fast");
//        });
//    }
//    else {
//        intervalID = setInterval("autoShowFloatingBox()", secondsPerPage * 1000);
//        $("#floatingBoxPause").fadeOut("fast", function() {
//            $(this).css("background-image", "url(/images/pause.png)").text("PAUSE").fadeIn("fast");
//        });
//    }
//}

function autoShowFloatingBox() {
    var pageCount = $(".floatingBoxContents").length;
    curIdx = (curIdx % pageCount) + 1;
    showFloatingBoxPage();
}

function goToFloatingBoxPage(idx) {
    curIdx = idx;
    showFloatingBoxPage();
//    if (intervalID != 0) {
//        clearInterval(intervalID);
//        intervalID = setInterval("autoShowFloatingBox()", secondsPerPage * 1000);
//    }
}

function showFloatingBoxPage(cb) {
    // Extract and show content
    var pageCount = $(".floatingBoxContents").length;
    if (pageCount > 0) {
        var idx = Math.min(pageCount - 1, Math.max(0, parseInt(curIdx) - 1)); // Constrain bounds
        // Fade out current content, then fade in new content
        $("#floatingBoxHead span").fadeOut(function() { $("#floatingBoxHead span").html("&nbsp;"); });
        $("#floatingBoxLink").fadeOut(function() { $("#floatingBoxLink").html("&nbsp;"); });
        $("#floatingBoxBodyContent").fadeOut("normal", function() {
            $("#floatingBoxBodyContent").html("&nbsp;");
            var box = $(".floatingBoxContents:eq(" + idx + ")");
            if (box != null) {
                $("#floatingBoxHead span").html($(".floatingBoxHead:first", box).html());
                $("#floatingBoxLink").html($(".floatingBoxLink:first", box).html());
                $("#floatingBoxBodyContent").html($(".floatingBoxContent:first", box).html());
            }
            $("#floatingBoxHead span").fadeIn();
            $("#floatingBoxLink").fadeIn();
            $("#floatingBoxBodyContent").fadeIn();
            if (cb != null) {
                cb();
            }
        });

        // Set all pagination links to "off"
        $("#floatingBoxPageLinks .paginationLink").removeClass("on");

        // Turn on relevant page link
        $("#floatingBoxPage_" + curIdx).addClass("on");

        // Turn on Prev/Next links as applicable
        /*if (curIdx == 1 && pageCount <= 1) {
            $("#floatingBoxPage_Prev").attr("href", "javascript:return false;");
        } else {
            $("#floatingBoxPage_Prev").attr("href", "javascript:goToFloatingBoxPage(" + (parseInt(curIdx) - 1) + ");");
        }*/
        if (curIdx == pageCount && pageCount <= 1) {
            $("#floatingBoxPage_Next").attr("href", "javascript:return false;");
        } else {
            $("#floatingBoxPage_Next").attr("href", "javascript:goToFloatingBoxPage(" + ((parseInt(curIdx) % pageCount) + 1) + ");");
        }
    } else {
        // Hide Prev/Next links
        //$("#floatingBoxPage_Prev").hide();
        $("#floatingBoxPage_Next").hide();
    }
}

function viewAsset(id) {
    // IE6 doesn't understand height and width of 100%, so let's calculate it manually here.
    $("#lightBoxBG").height($(document).height()).width($(document).width());
    $("#lightBoxBG").css("opacity", 0).show().fadeTo("normal", 0.8, function() {
        // Calculate where to show the lightbox
        var wh = getWindowWH();
        var xy = getScrollXY();
        var width = wh[0];
        var height = wh[1];
        var scrollX = xy[0];
        var scrollY = xy[1];

        var lightBoxWidth = 786;
        var lightBoxHeight = 573;

        var lightBoxLeft = Math.max(scrollX, scrollX + (width / 2) - (lightBoxWidth / 2));
        var lightBoxTop = Math.max(scrollY, scrollY + (height / 2) - (lightBoxHeight / 2));

        $("#lightBox").css("top", lightBoxTop + "px").css("left", lightBoxLeft + "px").fadeIn(function() {
            $("#lightBoxCloseButton").fadeIn("fast");
            $("#assetLightBoxIFrame").fadeIn("fast", function() {
                $("#assetLightBoxIFrame").attr("src", "/AssetViewerLightBox.aspx?id=" + id);
            });
        });
    });
}

function closeAsset() {
    $("#lightBoxCloseButton").fadeOut("fast");
    $("#lightBox").fadeOut(function() {
        $("#assetLightBoxIFrame").fadeOut("fast", function() {
            $("#assetLightBoxIFrame").removeAttr("src");
            $("#lightBoxBG").fadeOut();
        });
    });
}

function recommendAsset(id) {
    // Use cookies to track whether or not the current user has already recommended an asset
    var recommendation = readCookie("r" + id);
    if (recommendation == null) {
        var textBefore = $("#recommend_" + id).text();
        $.ajax({
            type: "GET",
            url: "/RecommendContent.aspx",
            data: { id: id },
            dataType: "text",
            cache: false,
            beforeSend: function() {
                // Change the link text to "Recommending..."
                $("#recommend_" + id).addClass("active").text("Recommending...");
            },
            success: function(text) {
                showAssetMessage(id, "Your recommendation has been received. Thank you for your feedback!", function() {
                    // text contains the new count of recommendations for this content block
                    $("#recommend_" + id).removeClass("active").text("Recommend (" + text + ")");
                    createCookie("r" + id, "1", 365);
                });
            },
            error: function(xhr) {
                showAssetMessage(id, "The server encountered an error while processing your recommendation. Please try again later.", function() {
                    $("#recommend_" + id).removeClass("active").text(textBefore);
                });
            }
        });
    }
    else {
        showAssetMessage(id, "You have already recommended this item.  Thank you for your feedback!");
    }
}

function showAssetMessage(id, messageText, fn) {
    $("#asset_" + id).append($("#assetMessage"));
    $("#assetMessage > p").text(messageText);
    $("#assetMessage").hide().fadeIn("fast", function() {
        if (fn != null) { fn(); }
        setTimeout(function() {
            $("#assetMessage").fadeOut(1500, function() {
                $("#assetMessage > p").html("&nbsp;");
                $("#assetMessageContainer").append($("#assetMessage"));
            });
        }, 1500);
    });
}

function commentAsset(id) {

}

function submitPoll(pollID) {
    var checkedControls = $(".pollQuestions:first input:checked");
    if (checkedControls.length > 0) {
        // Fade in overlay
        $(".pollQuestions:first").fadeOut(function() {
            $("#pollBoxOverlay").fadeIn(function() {
                $.ajax({
                    type: "GET",
                    url: "/SubmitPoll.aspx",
                    data: {
                        pollID: pollID,
                        choice: $(checkedControls[0]).val()
                    },
                    dataType: "html",
                    cache: false,
                    beforeSend: function() {
                        // Disable the submit button
                        $("#btnSubmit").attr("disabled", "true");
                    },
                    success: function(html) {
                        loadPollResults(pollID);
                        createCookie("pollComplete_" + pollID, "1", 365);
                    },
                    error: function(xhr) {
                        $("#pollBoxContent").html("<h4>We're sorry.  An error has occurred with our polling system.  Please check back later.</h4>");
                        $("#pollBoxOverlay").fadeOut("fast");
                    }
                });
            });
        });
    }
}

function loadPollResults(pollID, cb) {
    $("#pollBoxContent").load("/PollResults.aspx?id=" + pollID + " #pollResults", function() {
        $(".pollResultValue").hide();
        $("#pollBoxOverlay").fadeOut("fast", function() {
            $(".pollResultRow").each(function() {
                // Extract the width value to use in animation
                var pct = $(".pollAnswerPct:first", this);
                if (pct != null) {
                    // pct is a string containing a floating-point number (2 dec places) and a % sign at the end.
                    // Truncate everything after the decimal point to get an integer.
                    var wholePct = pct.html().split(".")[0];
                    if (parseInt(wholePct) == 0) {
                        $(".pollResultValue", this).hide();
                    }
                    else {
                        $(".pollResultValue", this).animate({ width: wholePct + "%" }, 1500, "swing");
                    }
                }
            });
        });

        if (cb != null) { cb(); }
    });
}
