var nextTimerVal;
var intervalId;
var answerClicked = -1;

function displayNextQuestion()
{
    hideElement('answer');
    hideElement('comments');
    // if not playing a specific sport (sport_id is not a digit), update the sport name in the sport select menu
    var sportMenu = document.getElementById('sportMenu');
    if (document.getElementById('nextSportName') && 
        sportMenu.options[sportMenu.selectedIndex].value != parseInt(sportMenu.options[sportMenu.selectedIndex].value) )
    {
        var sportMenuText = sportMenu.options[sportMenu.selectedIndex].text;
        var nextSportName = '- ' + document.getElementById('nextSportName').innerHTML;
        sportMenuText = sportMenuText.replace(/- \w+$/, nextSportName);
        sportMenu.options[sportMenu.selectedIndex].text = sportMenuText;
    }
    showElement('question');
    intervalId = setInterval('incrementTimer()',100);
}

function rateQuestion(countdownId,rating,triviaId)
{          
    hideElement('rateQuestion');
    hideElement('passed');
    showElement('afterRate');
    submitRating(rating,triviaId);
    document.getElementById(countdownId).innerHTML = "3";
    functionToCall = displayNextQuestion;
    nextTimerVal = 24;
    setTimeout(function(){countdown(3,600, countdownId, functionToCall);},600);
}

function countdown( secondsLeft, pauseLength, displayId, functionToCall )
{
    secondsLeft -= 1;
    document.getElementById(displayId).innerHTML = secondsLeft;
    if( secondsLeft > 0 )
        setTimeout(function(){countdown(secondsLeft,pauseLength,displayId,functionToCall);},pauseLength);
    else
        functionToCall();
}

function incrementTimer()
{
    var timer = document.getElementById('timer');
    if (! timer) return;
    if (nextTimerVal == 10) 
    {
        window.clearInterval(intervalId);
        return;
    }
    nextTimerVal = parseFloat(timer.innerHTML) - 0.1;
    if (nextTimerVal <= 10) window.clearInterval(intervalId);
    timer.innerHTML = nextTimerVal.toFixed(1);
}

function hideElement(elementId)
{
    if(document.getElementById(elementId)) {
        document.getElementById(elementId).style.visibility = 'hidden';
        document.getElementById(elementId).style.display = 'none';
    }
}

function showElement(elementId)
{
    if(document.getElementById(elementId)) {
        document.getElementById(elementId).style.visibility = 'visible';
        document.getElementById(elementId).style.display = 'block';
    }
}

function submitRating(rating,triviaId)
{
        rating = rating*2;
        var postData = "type=trivia&rating="+rating+"&id="+triviaId;
        var sUrl = "/ajax/thumbs.php";
        YAHOO.util.Connect.asyncRequest('POST', sUrl, rateCallback, postData);
}


var teamModSuccess = function(response){
    if(response.responseText !== undefined){
            var div = document.getElementById('teamMod');
            div.innerHTML = response.responseText;
    }
}

var rateCallback = {};

function ajaxFanActionWrapper(profileID, actionID, elementID, actionText, userName, awardID, replyID, contextId, contextParams)
{
    ajaxFanAction(profileID, actionID, elementID, actionText, userName, awardID, replyID, contextId, contextParams);
    
}

function changeTriviaQueue(menuObj)
{
   var selectedValue = menuObj.options[menuObj.selectedIndex].value;

   if(selectedValue != '')
   {
      window.location = '/trivia.php?queue='+selectedValue;
   }
}

function changeTriviaSport(menuObj)
{
   var i = menuObj.selectedIndex;

   if(i != '')
   {
      window.location = '/trivia.php?sport_id='+menuObj.options[i].value;
   }
}

function changeTriviaTeam(menuObj)
{
   var i = menuObj.selectedIndex;

   if(i != '')
   {
      window.location = '/trivia.php?team_id='+menuObj.options[i].value;
   }
}

function submitAnswer(answerId,answer)
{
    window.clearInterval(intervalId);
    document.getElementById('timer_value_on_submit').value = document.getElementById('timer').innerHTML;
    document.getElementById('trivia_form_answer').value = answerId;
    if(answerClicked < 0) {
        document.triviaQuestionForm.submit();
    }
    answerClicked = answer;
}

function answerSelect(id)
{
    if(answerClicked < 0) {
        document.getElementById('answer_'+id).className='answerSelected';
        document.getElementById('answerContain_'+id).style.backgroundColor = '#FEEC78';
    }
}

function answerDeselect(id)
{
    if(answerClicked < 0) {
        document.getElementById('answer_'+id).className='answerSelect';
        document.getElementById('answerContain_'+id).style.backgroundColor = 'transparent';
    }
}

// toggle the rating explanation
// toggleType can be 'on' (show the given rating explanation), 'off' (hide it) or 'switch' (show this one and hide all others)
function toggleExplainRating(rating, toggleType)
{
    for(i=1; i<=5; i++)
    {
        // show or hide the expansion icon and explanation for this rating, depending on the settings
        if (i == rating)
        {
            document.getElementById('ratingExpand'+i).style.display = (toggleType == 'off') ? 'block' : 'none';
            document.getElementById('ratingExplain'+i).style.display = (toggleType == 'off') ? 'none' : 'block';
        }
        // we don't need to mess with the other ratings unless we are trying to switch
        else if (toggleType == 'switch')
        {
            document.getElementById('ratingExpand'+i).style.display = 'block';
            document.getElementById('ratingExplain'+i).style.display = 'none';         
        }
    }
}

// setup moderator form for image upload or normal submission
function triviaModFormSubmit(submitType)
{
    var errorMessage = '';
    if (submitType == 'image')
    {
        document.modRatingForm.action = '/ajax/image_upload_trivia.php'; 
        document.modRatingForm.target = 'imageUploadTarget'; 
    }
    // on a regular submission, we need to do error checking, and only submit the form if no errors
    else
    {
        // some of this does not apply to the flagged question queue
        processFlag = (document.modRatingForm.process_flag) ? document.modRatingForm.process_flag.value : '';
        // determine the selected rating
        var thisRating = 0;
        if (processFlag == 'denied')
        {
            thisRating = 1;
        }
        else if (processFlag == 'approved')
        {
            thisRating = 3;
        }
        else
        {
            for (i=0; i<document.modRatingForm.rating.length; i++) 
            {
    		    if (document.modRatingForm.rating[i].checked)
                {
                    thisRating = document.modRatingForm.rating[i].value;
                }
            }
        }
        // if no team selected, give warning (unless we are working in the flagged queue or we are denying the question)
        if (submitType != 'ratingOnly' && processFlag == '' && thisRating > 1 && document.modRatingForm.team_id1.options[ document.modRatingForm.team_id1.selectedIndex ].value == '0')
        {
            // abort if user does not confirm
            if (! confirm('This question does not have a team tag.  Please cancel and add one if a team tag is appropriate.  Or, click continue to not include one.'))
            {
                return;
            }
        }
        // if no rating selected, give error
        if (thisRating == 0)
        {
            errorMessage += "Please select a rating\n";
        }
        // if rating = 5 and this isn't an admin override
        else if (thisRating == 5 && submitType != 'ratingOnly')
        {
            // error if no image
            if (document.modRatingForm.orig_image.value == '' && document.modRatingForm.image_upload_success.value == 0)
            {
                errorMessage += "A question must have a picture to receive a 5 rating.  Please add one or modify the rating.\n";
            }
            // error if no explanation
            if (! document.getElementById('explanation') || document.getElementById('explanation').innerHTML == '')
            {
                errorMessage += "A question must have an explanation to receive a 5 rating.  Please add one or modify the rating.\n";
            }
            // if moderator edited question (and no errors so far), ask if they want to give 100 points anyway
            if (document.modRatingForm.mod_edited == 1 && errorMessage == '')
            {
                if (confirm("You edited this question you are rating a 5.  Would you like to still credit the creator +100 points?  (Note we generally credit on minor corrections such as typos)."))
                {
                    document.modRatingForm.rating_points_eligible.value = 'Y';
                }
            }
            else
            {
                document.modRatingForm.rating_points_eligible.value = 'Y';
            }
        }
        // if rating = 4, check for an image
        else if (thisRating == 4 && submitType != 'ratingOnly')
        {
            // error if no image
            if (document.modRatingForm.orig_image.value == '' && document.modRatingForm.image_upload_success.value == 0)
            {
                errorMessage += "A question must have a picture to receive a 4 rating.  Please add one or modify the rating.\n";
            }
        }
        // if rating = 1 (deny)
        else if (thisRating == 1)
        {
            var denyReason = document.modRatingForm.reason.options[ document.modRatingForm.reason.selectedIndex ].value;
            var denyReasonOther = document.modRatingForm.reason_other.value;
            var denyReasonDefault = 'Type in your reason';
            // error if no reason selected
            if (denyReason == '')
            {
                errorMessage += "Please select a reason for denying this question.\n";
            }
            // error if "other" reason selected, but nothing entered in other_reason
            else if (denyReason == 'Other' && (denyReasonOther == '' || denyReasonOther == denyReasonDefault) )
            {
                errorMessage += "Please enter a reason in text box\n";
            }
            else if (denyReasonOther == denyReasonDefault)
            {
                document.modRatingForm.reason_other.value = '';
            }
        }
        // if any errors occured, display the error message as an alert and exit
        if (errorMessage != '')
        {
            alert(errorMessage);
            return;
        }
        
        if (submitType != 'ratingOnly')
        {
            document.modRatingForm.action = '/trivia.php';
            document.modRatingForm.target = '';
        }
    }    
    document.modRatingForm.submit();
}

// For trivia create page: this enables and disables form fields when users select type of question
function selectQuestionType(whichType) 
{
    if (whichType == 'multi') 
    {
        if (document.pollform.question.value == defaultValue_question) document.pollform.question.value = '';
        document.pollform.question.readOnly = false;
        document.pollform.quote.readOnly = true;
    } 
    else
    {
        document.pollform.question.readOnly = true;
        if (whichType == 'Who Said It?')
        {
            document.pollform.quote.readOnly = false;
            if (document.pollform.quote.value == defaultValue_quote) document.pollform.quote.value = '';
        }
        else
        {
            document.pollform.quote.readOnly = true;
        }
    }
}	

// For trivia create page: this enables and disables tip fields as user moves focus from section to section
function displayTriviaTip(sectionNum) 
{
    for(i=1; i<=4; i++)
    {
        document.getElementById('triviaTip'+i).style.display = (sectionNum == i) ? 'block' : 'none';
    }
}