﻿//**** Load Events When Document Ready ****
$(document).ready(function() {

    // *** Voting ***
    (function() {
        var vote = { q: pageData.itemId };

        //Init vote links
        $("#contentData a.option").each(function() {

            if (hasVoted()) {
                $(this).click(showResults);
            }
            else {
                $(this).click(sendVote);
            }

        });

        function showResults() {

            vote.a = getAnswerId(this);

            $.ajax({
                type: "POST",
                url: "/CodeBase/WebServices/PollService.asmx/GetPollResults",
                data: "{'questionID': '" + vote.q + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(result) {
                    displayPollResults(result);
                },
                error: function(message) {
                    displayAjaxError(message);
                }
            });

            $("#pollResultsContent h3").addClass("error").text("SORRY!");
            $("#pollResultsContent p:first").addClass("error").html("Voting is limited to once a day.<br /> Come back to Eluxury tomorrow for another daily dose of inspiration.");

            $("#pollResultsContent").modal({
                opacity: 70,
                containerId: "dialogContainer",
                overlayId: "dialogOverlay",
                onShow: dailyView.refreshDialogContent
            });

            foldUpAnswers();
        }

        //When clicked an answer:
        // - submit through ajaj
        // - show dialog results
        // - track vote
        function sendVote() {

            vote.a = getAnswerId(this);

            if (hasVoted(vote.q)) { showResults.apply(this); return; }

            $.ajax({
                type: "POST",
                url: "/CodeBase/WebServices/PollService.asmx/SaveVoteAndGetResults",
                data: "{'questionID': '" + vote.q + "', 'answerID': '" + vote.a + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(result) {
                    displayPollResults(result);
                },
                error: function(message) {
                    displayAjaxError(message);
                }
            });

            $("#pollResultsContent").modal({
                opacity: 70,
                containerId: "dialogContainer",
                overlayId: "dialogOverlay",
                onShow: dailyView.refreshDialogContent
            });

            $.tracker.track(vote, "vote");

            //Save vote cookie 
            saveVoteHistory();

            foldUpAnswers();
        }

        function getAnswerId(link) {
            return $(link).attr("id").replace(/a\d*[_]/, "");
        }

        function hasVoted() {
            //If cookie is set for this question, user has voted (returns true for ANY STRING, when cookie not null) 
            return Boolean($.cookie('voted-' + vote.q));
        }

        function saveVoteHistory() {
            //Set voted cookie
            $.cookie('voted-' + vote.q, true, { expires: 1 });
        }

        function displayPollResults(result) {

            var arrResults = (typeof result.d) == 'string' ? eval('(' + result.d + ')') : result.d;
            var pollChart = $(".pollResults li");

            for (var i = 0; i < arrResults.length; i++) {
                //console.log('Vote Percentage For Answer ID ' + arrResults[i].AnswerID + ': ' + arrResults[i].VotePercentage + '(Votes: ' + arrResults[i].VoteCount + ')');

                $(pollChart[i]).find("cite strong").html(arrResults[i].VotePercentage + "%");

                //Calc new height based on container for px height
                var newHeight = $(pollChart[i]).find("div.result").height() * (arrResults[i].VotePercentage / 100);

                //Reset height (for ie6 bug)
                $(pollChart[i]).find("div.result div").css("height", "0px");

                //$(pollChart[i]).find("div.result div").animate({ "height": arrResults[i].VotePercentage + "%" }, 500, function() {
                //old version with percent height not working in IE6

                $(pollChart[i]).find("div.result div").animate({ "height": newHeight + "px" }, 500);
            }
        }

        function displayAjaxError(message) {
            alert(message);
        }
    })();

    //*** Handle height of dropdown

    //Cache height
    var heightWithAnswerList = $('#contentData').height();

    //Collapse answer list
    $('#answerList .answersBox').css("display", "none");

    //Reset to the cached height
    $('#contentData').height(heightWithAnswerList);


    //Highlighting of poll answers
    $('#contentData h1.poll a').hover(function() {
        $('#contentData h1.poll').addClass("dark");
        $('#contentData h1.poll a').addClass("dark");
        $(this).removeClass("dark");
        $(this).addClass("light");
        Cufon.refresh("h1.poll");
    }, function() {
        $('#contentData h1.poll').removeClass("dark");
        $('#contentData h1.poll a').removeClass("dark");
        $(this).removeClass("light");
        Cufon.refresh("h1.poll");
    });

    $('#answerList a').hover(function() {
        $('#answerList a').addClass("dark");
        $(this).removeClass("dark");
        $(this).addClass("light");
        Cufon.refresh("#answerList a");
    }, function() {
        $('#answerList a').removeClass("dark");
        $(this).removeClass("light");
        Cufon.refresh("#answerList a");
    });

    //Setup "select one" dropdown
    $('#answerList a.foldDownButton').click(function(e) {
        e.preventDefault();
        var container = $('#answerList');
        container.find('div.blankBox').hide();

        container.find('div.answersBox').css("display", "none");
        container.find('div.answersBox').css("visibility", "visible"); /* needed to have it visibilty:hidden to calc height for centering */

        //@WARNING reference to global Cufon object!!!
        Cufon.replace('#answerList .multiAnswerItem a', { fontFamily: FontSettings.normal, hover: true });

        container.find('div.answersBox').slideDown();
    });

    $('#answerList a.foldUpButton').click(function(e) {
        e.preventDefault();
        foldUpAnswers();
    });

    var foldUpAnswers = function() {

        var container = $('#answerList');
        container.find('div.answersBox').slideUp(function() {
            container.find('div.blankBox').fadeIn("fast");
        });
    };

    // *** adjustWidth **********************************
    (function() {
        var answerList = $("#contentData #imageList");
        var minWidth = 300;
        var answerListWidth = 0;

        $(window).load(function() {

            answerList.find(".answer").each(function() {
                var imgwidth = $(this).find("img").width();
                answerListWidth = (imgwidth < minWidth) ? answerListWidth + minWidth : answerListWidth + imgwidth;
                $(this).css("width", (imgwidth < minWidth) ? minWidth : parseInt(imgwidth) + 15)
            });

            answerList.css("width", parseInt(answerListWidth) + 30);

            answerList.find(".answer img").css("visibility", "visible");
            answerList.find(".answer .caption").show();
        });

    })();


    // *** Credits **********************************
    (function() {
        $('#contentData a.creditsLink').click(function(e) {
            e.preventDefault();
            $(this).siblings(".credits").fadeToggle(500);
        });
    })();

    // *** Helpers **********************************
    jQuery.fn.fadeToggle = function(speed, easing, callback) {
        return this.animate({ opacity: 'toggle' }, speed, easing, callback);
    };

});