var questionsToCheck = {};
var numPages = 0;
var currentPage = 1;
var questionLookup = {};
var optionQs = {};
var pageToQuestion = {};

$(document).ready(function() {
    $('.back').bind('click', function() {
        previousPage();
    });

    $('.forward').bind('click', function() {
        nextPage();
    });

    numPages = $('.pageDiv').length;

    $('.clicktoproceed').bind('click', function() {
        nextPage();
    });

    $('#page_div_' + numPages + ' .clicktoproceed').css('display', 'none');
});

function switchQuestions(on, off)
{
    on = on.toString();
    off = off.toString();
    var onParts  = on.split(',');
    var offParts = off.split(',');
    for (var i = 0; i < onParts.length; i++) {
        if (onParts[i] != '') {
            questionOn(onParts[i]);
        }
    }

    for (var i = 0; i < offParts.length; i++) {
        if (offParts[i] != '') {
            questionOff(offParts[i]);
        }
    }
}


function questionOn(id)
{
    $('#question_' + id + '_wrap').css('display', 'block');
    questionsToCheck[id] = true;
}


function questionOff(id)
{
    $('#question_' + id + '_wrap').css('display', 'none');
    questionsToCheck[id] = false;
}

function nextPage()
{
    if (currentPage == numPages) {
        return;
    }

    if (checkPage(currentPage) == false) {
        return false;
    }

    submitPage();

    $('#page_div_' + currentPage).css('display', 'none');
    currentPage++;
    $('#page_div_' + currentPage).css('display', 'block');

    if (currentPage == 2) {
        showBack();
    }

    if (currentPage == numPages) {
        hideForward();
        submitValidQuestions();
    } else {
        showForward();
    }
}

function previousPage()
{
    if (currentPage <= 1) {
        return;
    }

    //if (checkPage(currentPage) == false) {
    //    return;
    //}

    $('#page_div_' + currentPage).css('display', 'none');
    currentPage--;
    $('#page_div_' + currentPage).css('display', 'block');

    if (currentPage == (numPages - 1)) {
        showForward();
    }

    if (currentPage == 1) {
        hideBack();
    } else {
        showBack();
    }

}

function hideBack()
{
    $('.back').css('display', 'none');
}

function showBack()
{
    $('.back').css('display', 'block');
}

function hideForward()
{
    $('.forward').css('display', 'none');
}

function showForward()
{
    $('.forward').css('display', 'block');
}

function checkPage(pageNum)
{
    if (pageNum < 3) {
        return true;
    }

    var messages = [];

    var currentQuestions = pageToQuestion[pageNum];
    for (var i = 0; i < currentQuestions.length; i++) {
        if (questionsToCheck[currentQuestions[i]]) {
            var questionMessage = checkQuestion(currentQuestions[i]);
            if (questionMessage != true) {
                messages = messages.concat(questionMessage);
            }
        }
    }

    if (messages.length != 0) {
        var startMessage = "Please provide answers for the following questions:\n\n";
        alert(startMessage + messages.join("\n"));
        return false;
    } else {
        return true;
    }

}

var submissionInProgress = false;

function submitPage()
{
    if (currentPage < 3) {
        return;
    }

    var formVals = $('#page_form_' + currentPage).serialize();
    submissionInProgress = true;
    $.post('/phs/index.php?url=pagesubmit', formVals, function(data) {
        submissionInProgress = false;
    });
}

function submitValidQuestions()
{
    var vals = [];
    for (var i in questionsToCheck) {
        if (questionsToCheck[i] == true) {
            vals.push(i);
        }
    }

    var formVals = {
        'validquestions[]': vals
    }
    submissionInProgress = true;
    $.post('/phs/index.php?url=validquestions', formVals, function(data) {
        submissionInProgress = false;
    });

}

function checkQuestion(id)
{
    var ret = [];
    if (optionQs[id]) {
      return true;
    }

    var currentQuestion = questionLookup[id];
    switch (currentQuestion['question_type']) {
        case 1:
        case 2:
            var checked = false;
            for (var i = 0; i < currentQuestion['components'].length; i++) {
                if ($('#' + currentQuestion['components'][i]['id'] + ':checked').val()) {
                    checked = true;
                    break;
                }
            }

            if (checked == false) {
                ret.push(currentQuestion['text']);
            }
        break;
        case 3:
        case 4:
            for (var i = 0; i < currentQuestion['components'].length; i++) {
                if (jQuery.trim($('#' + currentQuestion['components'][i]['id']).val()) == '') {
                    ret.push(currentQuestion['text']);
                }
            }
        break;
        case 5:
            for (var i = 0; i < currentQuestion['components'].length; i++) {
                if (!$('#question_' + id + '_yes_' + currentQuestion['components'][i]['option_id'] + ':checked').val() && !$('#question_' + id + '_no_' + currentQuestion['components'][i]['option_id'] + ':checked').val()) {
                    ret.push(currentQuestion['components'][i]['text']);
                }
            }
        break;
        case 6:
            for (var i = 0; i < currentQuestion['components'].length; i++) {
                if (jQuery.trim($('#' + currentQuestion['components'][i]['id']).val()) == '') {
                    ret.push(currentQuestion['components'][i]['text']);
                }
            }
        break;
        case 8:
        case 9:
            if ($('#question_' + id + ' :selected').val() == '') {
                ret.push(currentQuestion['text']);
            }
        break;
        case 10:
            if (!$('#question_' + id + '_usecm:checked').val() && !$('#question_' + id + '_usefeet:checked').val()) {
                ret.push(currentQuestion['text']);
                break;
            }

            if ($('#question_' + id + '_usecm:checked').val()) {
                if ($('#question_' + id + '_CM').val() == '') {
                    ret.push(currentQuestion['text'] + ': CM');
                }
            }

            if ($('#question_' + id + '_usefeet:checked').val()) {
                if ($('#question_' + id + '_FEET').val() == '') {
                    ret.push(currentQuestion['text'] + ': Feet');
                }

                if ($('#question_' + id + '_INCHES').val() == '') {
                    ret.push(currentQuestion['text'] + ': Inches');
                }
            }
        break;
        case 11:
            if (!$('#question_' + id + '_usekg:checked').val() && !$('#question_' + id + '_usestone:checked').val()) {
                ret.push(currentQuestion['text']);
                break;
            }

            if ($('#question_' + id + '_usekg:checked').val()) {
                if ($('#question_' + id + '_KG').val() == '') {
                    ret.push(currentQuestion['text'] + ': KG');
                }
            }

            if ($('#question_' + id + '_usestone:checked').val()) {
                if ($('#question_' + id + '_ST').val() == '') {
                    ret.push(currentQuestion['text'] + ': Stone');
                }

                if ($('#question_' + id + '_POUNDS').val() == '') {
                    ret.push(currentQuestion['text'] + ': Pounds');
                }
            }
        break;
    }

    if (ret.length == 0) {
        ret = true;
    }

    return ret;
}

var pools = {};

function checkPool(questionIDs)
{
    questionIDs = questionIDs.toString();
    var parts   = questionIDs.split(',');
    for (var i in parts) {
        var currQ = parts[i];
        var yesExists = false;
        for (var i in pools[currQ]) {
            // Check each to see if there is still a valid radio box checked, if
            // there is then we can exit as we know the question should be shown.
            // If there aren't any yes answers, we should hide it.
            if ($('#question_' + pools[currQ][i]['parentQuestion'] + '_yes_' + pools[currQ][i]['optionID'] + ':checked').length == 1) {
                // Yes is checked for this questions parent, keep it shown and break out.
                yesExists = true;
                break;
            }
        }

        if (yesExists == false) {
            // Hide Q
            questionOff(currQ)
        } else {
            // Show Q
            questionOn(currQ)
        }
    }


}

function addToPool(questionID, parentQuestion, optionID)
{
    questionID = questionID.toString();
    var parts = questionID.split(',');
    for (var i in parts) {
        var currQ = parts[i];
        if (!pools[currQ]) {
            pools[currQ] = [];
        }

        pools[currQ].push({
                      parentQuestion: parentQuestion,
                      optionID: optionID
                     });
    }

}
