var last_index = 0;
var game_open = false;
var current_quiz_page = "landing";
var current_quiz = 1;
var current_question = 0;
var choices = new Array();
var questions_max = 5;

$(document).ready(function(){
    new Accordion("#poll_accordion", {active_tab: 0});
    new VerticalScrollBox("#poll_scrollbox", 336);
    
    new Accordion("#download_accordion", {active_tab: 0});
    new VerticalScrollBox("#download_scrollbox", 150);

    new Accordion("#quizzes_accordion", {active_tab: 0});
    new VerticalScrollBox("#quizzes_scrollbox", 150);

    new VerticalScrollBox("#complete_list", 150);
    //div#complete_list ul#games_listing

    refresh_arrow_visibility("#complete_list");
    refresh_arrow_visibility("#download_scrollbox");
    refresh_arrow_visibility("#quizzes_scrollbox");

    // View more info on game
    $('#games_listing a').click(function() {
        var gameLinkClick = $('#games_listing a').index(this) + 1;

        $('#chosen_game_placeholder div.chosen_game').fadeOut('fast');
        setTimeout(function() {
            $('#chosen_game_placeholder div.chosen_game:nth-child(' + gameLinkClick + ')').fadeIn('medium');
        },400);
          
        return false;
    });
    
    $("#download_scrollbox .body .download_body a").live("click", function(event){
        var confirm_str = $("#legalMessages .download").text();
        if(!confirm(confirm_str)){
            event.preventDefault();
            return false;
        }
        
        return true;
    });
    
    // Start Game
    $('#games_utility div.chosen_detail a.small_arrow_button,#games_utility #chosen_game_placeholder .chosen_game img').click(function() {
        stopGame();
        
        var self = this;
        setTimeout(function(){
            var gameLinkClick = $('#games_utility div.chosen_detail a.small_arrow_button').index(self) + 1;
            if (!gameLinkClick)
                var gameLinkClick = $('#games_utility #chosen_game_placeholder .chosen_game img').index(self) + 1;

            return startGame(gameLinkClick);
        },650);
    });
    
    // Close game
    $('#games_utility #playing_game a.small_arrow_button').click(function() {
        stopGame();
    });
    
    $('#chosen_game_placeholder div.chosen_game:nth-child(1)').fadeIn('medium');
    $('#playing_game div.flash_game:nth-child(1)').css('display','none');
    
     
     if ($('div.slider_advertisements div.ad').size() > 1)
     {
         $('#fun_games_pagination').css('display','block');
     }
     
    $('.page_left').click(function() {
        slideContents('left','div.slider_advertisements','div.ad','.ad_links');
        setTimeout(function() {
            updatePageLinkOnstate('div.slider_advertisements','div.ad','.ad_links');
        },450);
        return false;
    });
    $('.page_right').click(function() {
        slideContents('right','div.slider_advertisements','div.ad','.ad_links');
        setTimeout(function() {
            updatePageLinkOnstate('div.slider_advertisements','div.ad','.ad_links');
        },450);
        return false;
    });
    $('.ad_links li.page_link a').click(function() {
        var pageLinkClick = $('.ad_links li.page_link a').index(this);
        updatePageLinks('div.slider_advertisements','div.ad','.ad_links',pageLinkClick);
        return false;
    });
    $('.page_left img.page_left_on').fadeOut('fast');
    
     
    // Poll
    $('div.individual_poll a.small_arrow_button').click(function() {
        if(is_logged_in){
            var optionChosen = null;
            var pollChosen = $(this).closest("div.individual_poll").attr('id');
            
            $("#poll_scrollbox .individual_poll span.radio").each(function(){
                if($(this).css('background-position') == '0px -30px'){
                    optionChosen = $(this).attr('id').replace("poll_choice", "");
                }
            });

            // optionChosen = option selected
            if($.cookie('votedIn_' + pollChosen) != '1'){
                voteInPoll(pollChosen, optionChosen);
            }
            return false;
		  }
		  else
		  {
			  return true;
		  }
    });
    $('div.individual_poll').each(function() {
        var chosenPollID = $(this).attr('id');

        if ($.cookie('votedIn_' + chosenPollID) == 1){
            pollDisplay(chosenPollID, 'results');
        }
        else{
            pollDisplay(chosenPollID, 'poll');
        }
    });
     
    // Login to vote
    if(!is_logged_in){
        $('#poll_scrollbox div.poll_voting a.small_arrow_button div.middle_inner').html($("#sharedServicesMessages .loginToVote").text());
		  $('#poll_scrollbox div.poll_voting a.small_arrow_button').attr('href','login.action');
    }


    $("#goto_landing").click(function(){
        if(current_quiz_page != "landing"){
            quiz_change_screens("landing");
            current_quiz_page = "landing";
        }
    });
    $("#goto_results").click(function(){
        if(current_quiz_page != "results"){
            quiz_change_screens("results");
            current_quiz_page = "results";
        }
    });
    $("#goto_allquizzes").click(function(){
        if(current_quiz_page != "allquizzes"){
            quiz_change_screens("allquizzes");
            current_quiz_page = "allquizzes";
        }
    });
    $("#quizzes_landing_list div.line div.data a").click(function(){
        current_quiz = $(this).parent().attr("id").split("_")[3];
        quiz_change_screens("allquizzes");
    });
    $("#quizzes_allquizzes .backtoquizzes").click(function(){
        quiz_change_screens("landing");
    });
    $("#quizzes_results .moreQuizzes").click(function(){
        quiz_change_screens("landing");
    });

    $("#quizzes_overlay .back").click(function(){
        current_question--;
        
        $("#quizzes_overlay").animate({
            marginLeft: "-347px"
        }, 400, "swing", function(){
            quiz_populate_quiz();
            quiz_check_buttons();
            $("#quizzes_overlay").animate({
                marginLeft: "0px"
            });
        });
    });

    $("#quizzes_overlay .next").click(function(){
        var val = $("#quizzes_choice_list li input:checked").val();
        if(!val)
            return;
        
        choices[current_question] = val;
        
        current_question++;
        $("#quizzes_overlay").animate({
            marginLeft: "347px"
        }, 400, "swing", function(){
            quiz_populate_quiz();
            quiz_check_buttons();
            $("#quizzes_overlay").animate({
                marginLeft: "0px"
            });
        });
    });
    
    $("#quizzes_overlay .finish").click(function(){
        var val = $("#quizzes_choice_list li input:checked").val();
        if(!val)
            return;
        
        choices[current_question] = val;
        
        if(current_question == (questions_max-1)){
            quiz_populate_results();
            quiz_change_screens("results");
        }    
    });
});

function stopGame(){
    $('#playing_game div.flash_game').fadeOut('fast', function(){
        $("#flash_write" + last_index).remove();
        $("#flashinfo"+last_index).parent().append("<div id=\"flash_write"+last_index+"\" style=\"width:725px;height:443px;\"");
    });
    setTimeout(function() {
        $('#playing_game').slideUp('medium');
        game_open = false;
    },600);
}

function startGame(gameLinkClick){
    game_open = true;
    
    $('#playing_game').slideDown('medium');
    var useLookup;
    if (parseInt(gameLinkClick) == 1)
        useLookup = ':first';
    else
        useLookup = ':nth-child(' + gameLinkClick + ')';

    if ($('#flash_write' + gameLinkClick).closest('div.flash_game').css('display') == 'none'){
        setTimeout(function() {
            $('#flash_write' + gameLinkClick).closest('div.flash_game').show('fast');
            embed_game_flash(gameLinkClick);
        },600);
    }
    var gameLinkTotal = $('#games_listing a').length;
    return false;
}

function pollDisplay(chosenPollID,displayType)
{
    if (displayType == 'poll')
    {
        $('#' + chosenPollID + ' .poll_results').css('display','none');
        $('#' + chosenPollID + ' .poll_voting').css('display','block');
        refresh_arrow_visibility("#poll_scrollbox");
    }
    else if (displayType == 'results')
    {
        $('#' + chosenPollID + ' span.poll_percent_value').css('display','none');
        $('#' + chosenPollID + ' div.poll_result_graph').css('width','0%');
        $('#' + chosenPollID + ' .poll_voting').fadeOut('fast',function() {
        
            // Get a list of all answer ids
            var allIds = new Array();
            var idsPerPoll = new Object();
            $("#poll_scrollbox .individual_poll span.radio").each(function(){
                var id = $(this).attr('id').replace('poll_choice','');
                allIds.push(id);
                
                if(!idsPerPoll[chosenPollID])
                    idsPerPoll[chosenPollID] = new Array();
                    
                idsPerPoll[chosenPollID].push(id);
            });

            // Get html of all polls with answer data
            $.get("ss.action?service=/v2/m1/xml/survey/generic/survey/getSurveyDetails&template=getSurveyDetails&noflash=1&alfrescoAnswerIds=" + allIds.join(",") + "&referer=games"+getCredentials(), {}, function(data, textStatus){
                
                // Go through each poll and add up the answers and counts
                var answers = new Object();
                $(data).children("div").each(function(){
                    var pollId = $(this).attr("id");

                    answers[pollId] = new Object();
                    answers[pollId]['total'] = 0;
                    answers[pollId]['answers'] = new Array();
                    $(this).find("div.poll_results .hidden_count").each(function(){
                        var answerId = $(this).attr("id").replace("answer_", "");

                        // If the response is empty, save it as 0
                        var count = 0;
                        if($(this).text() != "")
                            count = parseInt($(this).text());

                        answers[pollId]['answers'].push({
                            answerId: answerId,
                            count: count
                        });
                        
                        answers[pollId]['total'] += count;
                    });
                });
                
                // Refresh the poll html
                $('#' + chosenPollID + ' .poll_results').html($(data).find('#' + chosenPollID + ' .poll_results').html());
                
                refresh_arrow_visibility("#poll_scrollbox");

                // Fade in the new poll html
                $('#' + chosenPollID + ' .poll_results').fadeIn('fast',function() {
                    if(answers[chosenPollID]){
                        for(var i=0; i<answers[chosenPollID]['answers'].length; i++){
                            var pollOptionNow = answers[chosenPollID]['answers'][i].answerId;
                            var myWidth = Math.floor((answers[chosenPollID]['answers'][i].count/answers[chosenPollID]['total'])*100);
                            
                            // Set the widget of the result bar
                            $('div#poll_graph' + pollOptionNow).animate({
                                width: myWidth + "%"
                            },400);
                            
                            // Set the label of the result bar
                            $('div#poll_graph' + pollOptionNow + ' span.poll_percent_value').html(myWidth + '%');
                        }
                    }
                    $('#' + chosenPollID + ' span.poll_percent_value').fadeIn('slow');
                });
            }, "html");
        });
    }
}

function voteInPoll(pollId, answerId){
    $.get("ss.action?service=/v2/m1/xml/survey/generic/survey/voteForSurveyAnswer&template=setWithStatus&noflash=1&alfrescoAnswerId="+answerId+getCredentials(), {}, function(data, textStatus){
        if(sharedServicesSuccess(data)){
            var key = "votedIn_" + pollId;
            $.cookie(key, '1');
            
            awardUser("poll_vote_" + pollId.replace("poll_id_", ""), function(data){
                var msg = $(data).find("root message").text();
                var charm = $(data).find("root charms item[1] assets[size=1] BAS").text();
                
                showAwardPopup(msg, charm, -50, 725);
            });
            
            setTimeout(function() {
                $('#' + pollId + ' #pollResultDisplay').fadeOut('fast');
                pollDisplay(pollId, "results");
            },1000);
        }
        else
            $('#' + pollId + ' .error').html(closeButton);
    }, "xml");
}

function embed_game_flash(index){
    var externalGameUrl = $("#flashinfo"+index+" .externalGameUrl").text();
    
    if(externalGameUrl != ""){
        var iframe = "<iframe src=\"" + externalGameUrl + "\" style=\"width:725px;height:443px;\" scrolling=\"no\" marginwidth=\"0\" marginheight=\"0\" frameborder=\"0\" vspace=\"0\" hspace=\"0\"></iframe>";
        $("#flash_write"+index).html(iframe);
    }
    else{
        var flashvars = {
            contentpath: $("#flashinfo"+index+" .flashSwf").text(),
            accountId: ($.cookie("userId") ? $.cookie("userId") : 0),
            xmlpath: $("#flashinfo"+index+" .flashXml").text(),
            requestorId: "casual-charmgirlsclub",
            username: ($.cookie("displayName") ? $.cookie("displayName") : 0),
            personaId: ($.cookie("personaId") ? $.cookie("personaId") : 0),
            ssbase: "/ss.action?service="
        };
        var params = {
            menu: "false",
            wmode: "window",
            bgcolor: "#f7d9fb",
            allowFullScreen: "false",
            allowScriptAccess: "always"
        };
        var attributes = {
            name: "flash_swf"
        };
        swfobject.embedSWF(
            "Shell.swf", 
            "flash_write"+index, 
            "725", "443", "9.0.0.0", "expressInstall.swf", 
            flashvars, 
            params,
            attributes
        );
    }
    
    last_index = index;
}


function quiz_change_screens(to){
    $("#quizzes_overlay").fadeOut("slow");
    
    setTimeout(function(){
        $("#quizzes_accordion .quizzes_screen").hide();
        
        if(to == "allquizzes"){
            current_question = 0;
            choices = new Array();
            quiz_populate_quiz();
            quiz_check_buttons();
        }
        
        $("#quizzes_" + to).show();
        $("#quizzes_overlay")
            .css("backgroundImage", "url(images/quizzes/" + to + "_overlay.png)")
            .fadeIn("slow");
    }, 550);
}

function quiz_populate_quiz(){
    var choice_index = 0;
    var quiz = $("#quizzes_hidden .quiz:eq(" + (current_quiz-1) + ")");
    var questionAndChoices = quiz.find(".questionAndChoices:eq(" + current_question + ")");
    
    // Populate the quiz question
    $("#quizzes_quiz_title").html(questionAndChoices.children(".question").html());
    
    // Populate the quiz choices    
    $("#quizzes_choice_list").html("");
    questionAndChoices.children(".choice").each(function(){
        var choice_id = "quiz_" + (current_quiz-1) + "_choice_" + choice_index;
        var checked = (choices[current_question]==choice_index ? " checked" : "");
        $("#quizzes_choice_list").append("<li><input type=\"radio\" id=\"" + choice_id + "\" value=\"" + choice_index + "\" name=\"question\"" + checked + " /> <label for=\"" + choice_id + "\">" + $(this).html() + "</label></li>\n");
        choice_index++;
    });
    
    // Update the position display
    $("#quizzes_allquizzes .navigation .position").html((current_question+1) + " / " + questions_max);
}

function quiz_check_buttons(){
    if(current_question == 0)
        $("#quizzes_allquizzes .navigation .back").css("visibility", "hidden");
    else
        $("#quizzes_allquizzes .navigation .back").css("visibility", "visible");

    $("#quizzes_allquizzes .navigation .next").hide();
    $("#quizzes_allquizzes .navigation .finish").css("visibility", "hidden");
    if(current_question == (questions_max-1)){
        $("#quizzes_allquizzes .navigation .finish").css("visibility", "visible");
    }
    else{
        $("#quizzes_allquizzes .navigation .next").show();
    }
}

function quiz_populate_results(){
    var results = new Array();
    results[0] = 0;
    results[1] = 0;
    results[2] = 0;

    var quiz = $("#quizzes_hidden .quiz:eq(" + (current_quiz-1) + ")");
    
    // Add up the results
    for(var i=0; i<choices.length; i++)
        results[choices[i]]++;

    // Get the most chosen choice number
    var chosen_index = 0;
    for(var i=0; i<results.length; i++){
        if(results[i] > results[chosen_index])
            chosen_index = i;
    }

    // Populate the result strings
    $("#result_content .results_subheader").html(quiz.children(".resultSubheader").html());
    $("#result_content .result").html(quiz.children(".result:eq(" + chosen_index + ")").html());
    
    if(is_logged_in){
        $("#quizzes_notloggedin").css("visibility", "hidden");

        awardUser("quiz_taken", function(data){
            var msg = $(data).find("root message").text();
            var charm = $(data).find("root charms item[1] assets[size=1] BAS").text();

            showAwardPopup(msg, charm, 557, 725);
        });
    }
    else{
        $("#quizzes_notloggedin").css("visibility", "visible");
    }
}
