
/* Browser Check */
var browser_is_ie = false;
if( navigator.appVersion.indexOf( "MSIE" ) != -1 )
{   temp = navigator.appVersion.split( "MSIE" );
    version = parseFloat( temp[1] );
    if( version >= 5.5 )
    {   browser_is_ie = true;
    }
}
addLoadEvent( function()
    {   if( !browser_is_ie )
        {   document.getElementById( 'browser_specific_warning' ).innerHTML = "<i> Your browser does not " +
                        "show image previews. Please select images carefully, because you won't be able to " +
                        "change them. </i><br /><br />";
        }
    }
);

var default_question_count = 4;
var min_question_count = 4;
var max_question_count = 100;
var load_previous_questions = false;
var questions = new Array();
var load_previous_answers = false;
var answers = new Array();
var correctAnswers = new Array();
var num_results = 4;
var no_photo_selected = contextPath + "/images/quiz/no_photo_selected_200.gif";
var quiz_photo_selected = contextPath + "/images/quiz/quiz_photo_selected_200.gif";
var result_photo_selected = contextPath + "/images/quiz/result_photo_selected_200.gif";


/* Question functions */

function setCheckedValue(){
	 var href = document.getElementById("link1").href;
	 var index = href.lastIndexOf('/');
	 var href = href.substring(0,index);
	 
	 if(document.getElementsByName("questionAnswers")[0].checked){
		document.getElementById("link1").href = href+"/1";
		document.getElementById("link2").href = href+"/1";
	  }else if(document.getElementsByName("questionAnswers")[1].checked){
		document.getElementById("link1").href = href+"/2";
		document.getElementById("link2").href = href+"/2";
	   }else if(document.getElementsByName("questionAnswers")[2].checked){
		 document.getElementById("link1").href = href+"/3";
		 document.getElementById("link2").href = href+"/3";
	    }else if(document.getElementsByName("questionAnswers")[3].checked){
		 document.getElementById("link1").href = href+"/4";
		 document.getElementById("link2").href = href+"/4";
	    }else if(document.getElementsByName("questionAnswers")[4].checked){
		 document.getElementById("link1").href = href+"/5";
	 	 document.getElementById("link2").href = href+"/5";
	   }
  }


function addSingleQuestion( n )
{   if( load_previous_questions )
    {   value = questions[n];
    }
    else
    {   value = "Enter Question Here";
    }
    if( load_previous_answers )
    {   answer_clean_array = Array();
        for( var i = 1; i <= 4; i++ )
        {   ans_txt = answers[( ( n - 1 ) * 4 ) + i];
            ans_txt = ans_txt.replace( /"/g, '&#34;' );
            ans_txt = ans_txt.replace( /'/g, '&#39;' );
            answer_clean_array[i] = ans_txt;
        }
        ans1 = answer_clean_array[1];
        ans2 = answer_clean_array[2];
        ans3 = answer_clean_array[3];
        ans4 = answer_clean_array[4];
    }
    else
    {   ans1 = "Answer (A) Here";
        ans2 = "Answer (B) Here";
        ans3 = "Answer (C) Here";
        ans4 = "Answer (D) Here";
    }

    el = document.getElementById( 'quiz-questions' );
    newdiv = document.createElement( 'div' );
    newdiv.id = 'q' + n + '_div';
    newdiv.className = "smallText";
    str = "";
    newdiv.innerHTML = '\
        <div style="position:relative;"> \n\
            <div class="quiz-question-title"> \n\
                <span style="position:relative; top:4px;">' + n + '. </span> \n\
                <span id="q' + n + '_input"><textarea name="q' + n + '" tabIndex=' + (10*n) + ' class="bodyText form-hover" style="width:440px; vertical-align:top; height:38px;">'+value+'</textarea></span> \n\
                <span id="q' + n + '_delete"><a href="#" class="tinyText disable-delete">Delete</a></span> \n\
            </div> \n\
            <div id="q'+n+'_suggest"   class="tinyText" style="position:absolute; top:75px; left:-5px; width:80px; text-align:center; color:#999999; background:url(http://icons.sconex.com/arrow_right_gray.gif) no-repeat center right;"></div> \n\
            <div id="q'+n+'_warning" class="tinyText" style="position:absolute; top:75px; left:-5px; width:80px; text-align:center; color:red; background:url(http://icons.sconex.com/arrow_right_red.gif) no-repeat center right;"></div> \n\
            <table cellspacing=0 class="trivia-answers"> \
                <tr><td id="q'+n+'_a1_ok" style="color:green; width:60px;" class="tinyText" align=right></td> \
                    <td class="answers"><span id="q'+n+'_a1"><input type="radio" name="q'+n+'_correct" value=1 class=""><input type="text" name="q'+n+'_a1" tabIndex =' + (10*n + 1) + ' name="1"  value="'+ans1+'" class="form-hover" style="width:350px;"></span></td></tr> \
                <tr><td id="q'+n+'_a2_ok" style="color:green; width:60px;" class="tinyText" align=right></td> \
                    <td class="answers"><span id="q'+n+'_a2"><input type="radio" name="q'+n+'_correct" value=2 class=""><input type="text" name="q'+n+'_a2" tabIndex =' + (10*n + 2) + '  name="1" value="'+ans2+'" class=" form-hover" style="width:350px;"></span></td></tr> \
                <tr><td id="q'+n+'_a3_ok" style="color:green; width:60px;" class="tinyText" align=right></td> \
                    <td class="answers"><span id="q'+n+'_a3"><input type="radio" name="q'+n+'_correct" value=3 class=""><input type="text" name="q'+n+'_a3" tabIndex =' + (10*n + 3) + '  name="1" value="'+ans3+'" class=" form-hover" style="width:350px;"></span></td></tr> \
                <tr><td id="q'+n+'_a4_ok" style="color:green; width:60px;" class="tinyText" align=right></td> \
                    <td class="answers"><span id="q'+n+'_a4"><input type="radio" name="q'+n+'_correct" value=4 class=""><input type="text" name="q'+n+'_a4" tabIndex =' + (10*n + 4) + '  name="1" value="'+ans4+'" class=" form-hover" style="width:350px;"></span></td></tr> \
            </table> \
        </div> \
    ';
    addEffectToInput( newdiv.getElementsByTagName( 'textarea' )[0] );
    input_els = newdiv.getElementsByTagName( 'input' );
    addEffectToInput( input_els[1] );
    addEffectToInput( input_els[3] );
    addEffectToInput( input_els[5] );
    addEffectToInput( input_els[7] );
    input_els[0].onclick = function(){ updateSuggestionToTriviaQuestion( n ); };
    input_els[2].onclick = function(){ updateSuggestionToTriviaQuestion( n ); };
    input_els[4].onclick = function(){ updateSuggestionToTriviaQuestion( n ); };
    input_els[6].onclick = function(){ updateSuggestionToTriviaQuestion( n ); };
    if( load_previous_answers )
    {   correct_answer = correctAnswers[n];
        if( correct_answer != "none" )
        {   newdiv.getElementsByTagName( 'input' )[( ( correct_answer - 1 ) * 2 )].checked = true;
        }
    }
    el.appendChild( newdiv );
}

function addQuestion()
{   if( question_count >= max_question_count )
    {   alert( "You can have no more than " + max_question_count + " questions." );
        return false;
    }
    question_count++;
    addSingleQuestion( question_count );
    updateSuggestionToTriviaQuestion( question_count );
    setQuestionDelete( question_count );
    setQuestionDeleteAll( false );
    updateResultScores();
    return false;
}

function removeQuestion(position)
{   if( question_count <= min_question_count )
    {   return false;
    }
    el = document.getElementById( 'quiz-questions' );
    if( position != question_count )
    {   //shuffle question ids around, fromdiv -> todiv
        for( i = position; i < question_count; i++ )
        {   old_input = document.getElementById( 'q' + i + '_input' ).firstChild;
            new_input = document.getElementById('q' + (i+1) + '_input').firstChild;
            old_input.value = new_input.value;
            for( j = 1; j <= 4; j++ )
            {   old_input = document.getElementById( 'q' + i + '_a' + j );
                new_input = document.getElementById( 'q' + ( i + 1 ) + '_a' + j );
                if( new_input.firstChild.checked )
                {   old_input.firstChild.checked = true;
                }
                old_input.lastChild.value = new_input.lastChild.value;
                old_input.lastChild.style.background = new_input.lastChild.style.background;
            }
            updateSuggestionToTriviaQuestion( i );
            updateSuggestionToTriviaQuestion( i + 1 );
        }
    }
    el.removeChild( el.lastChild );
    question_count--;
    setQuestionDeleteAll( false );
    updateResultScores();
    return false;
}

function setQuestionDelete(n)
{   el = document.getElementById( 'q' + n + '_delete' ).firstChild;
    if( question_count == min_question_count )
    {   el.className = "tinyText disable-delete";
        el.onclick = function(){ return false; }
    }
    else
    {   el.className = "tinyText";
        el.onclick = function(){ removeQuestion( n ); return false; }
    }
}

function setQuestionDeleteAll( bForceUpdate )
{   if( bForceUpdate || ( question_count == min_question_count ) || ( question_count == ( min_question_count + 1 ) ) )
    {   for( i = 1; i <= question_count; i++ )
        {   setQuestionDelete( i );
        }
    }
}


/* Update functions */
function updateResultPhoto(n)
{   el = document.getElementById( 'cat' + n + '-photo' ).firstChild;
    preview = document.getElementById( 'preview-cat' + n + '-photo' ).firstChild;
    preview_quiz = document.getElementById( 'preview-quiz-photo' ).firstChild;
    if( el.value == "" )
    {   preview.src = preview_quiz.src;
    }
    else
    {   if( browser_is_ie )
        {   preview.src = el.value;
        }
        else
        {   preview.src = result_photo_selected;
        }
    }
}

function updateQuizPhoto()
{   el = document.getElementById( 'quiz-photo' ).firstChild;
    preview = document.getElementById( 'preview-quiz-photo' ).firstChild;
    if( el.value == "" )
    {   preview.src = no_photo_selected;
    }
    else
    {   if( browser_is_ie )
        {   preview.src = el.value;
        }
        else
        {   preview.src = quiz_photo_selected;
        }
    }
    for( i = 1; i <= num_results; i++ )
    {   updateResultPhoto( i );
    }
}

function updateResultScores()
{   interval = Math.floor( ( 1 + question_count ) / num_results );
    remainder = ( 1 + question_count ) % num_results;
    previous_range = -1;
    for( i = 1 ; i <= num_results; i++ )
    {   floor = previous_range + 1;
        ceiling = previous_range + interval;
        if( remainder > 0 )
        {   ceiling++;
            remainder--;
        }
        el = document.getElementById( 'cat' + i + '-score' );
        if( floor == ceiling )
        {   el.innerHTML = floor;
        }
        else
        {   el.innerHTML = floor + " - " + ceiling;
        }
        previous_range = ceiling;
    }
}

function updateQuizTitle()
{   if( browser_is_ie )
    {   value = document.getElementById( 'quiz-title' ).firstChild.getAttribute( "value" );
    }
    else
    {   value = document.getElementById( 'quiz-title' ).firstChild.value;
    }
    for( i = 1 ; i <= num_results; i++ )
    {   el = document.getElementById( 'cat' + i + '-quiz-name' );
        el.innerHTML = value;
    }
}


/* Validation */
function validateSingleAnswer( qn, an )
{   el = document.getElementById( 'q' + qn + '_a' + an ).lastChild;
    if( ( el.value == "" )
        || ( el.value == "Answer (A) Here" )
        || ( el.value == "Answer (B) Here" )
        || ( el.value == "Answer (C) Here" )
        || ( el.value == "Answer (D) Here" ) )
    {   el.style.background = '#FFE0E0';
        bNoErrors = false;
    }
    else
    {   el.style.background = '#FFFFFF';
    }
}

function validateAnswers()
{   bNoErrors = true;
    for( var i = 1; i <= question_count; i++ )
    {
        for( var j = 1; j <= 4; j++ )
        {   validateSingleAnswer( i, j );
        }
    }
    return bNoErrors;
}

function validateQuizPhoto()
{   return ( document.getElementById( 'quiz-photo' ).firstChild.value != "" );
}

function validateSubmit()
{   vqp = validateQuizPhoto();
    vans = true; //validateAnswers();
    bErrorFree = vqp && vans;
    if( !bErrorFree )
    {   if( !vqp )
        {   alert( "You must select a photo for your quiz." );
        }
        if( !vans )
        {   alert( "You need at least four answers for each question." );
        }
    }
    else
    {   // disable the button (to prevent multiple submits)
        document.getElementById( 'quiz-submit' ).disabled = true;
        document.getElementById( 'quiz-submit-info' ).innerHTML = "Submitting quiz, please wait...";
    }
    return bErrorFree;
}


/* Set up the page */
function getElementsByClass( searchClass, node, tag )
{   var classElements = new Array();
    if( node == null )
    {   node = document;
    }
    if( tag == null )
    {   tag = '*';
    }
    var els = node.getElementsByTagName( tag );
    var elsLen = els.length;
    var pattern = new RegExp( "(^|\\s)"+searchClass+"(\\s|$)" );
    for( i = 0, j = 0; i < elsLen; i++ )
    {   if( pattern.test( els[i].className ) )
        {   classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

function updateSuggestionToTriviaQuestion( qid )
{   a1 = document.getElementById( 'q' + qid + '_a1' ).firstChild;
    a2 = document.getElementById( 'q' + qid + '_a2' ).firstChild;
    a3 = document.getElementById( 'q' + qid + '_a3' ).firstChild;
    a4 = document.getElementById( 'q' + qid + '_a4' ).firstChild;
    a1_ok = document.getElementById('q'+ qid + '_a1_ok');
    a2_ok = document.getElementById('q'+ qid + '_a2_ok');
    a3_ok = document.getElementById('q'+ qid + '_a3_ok');
    a4_ok = document.getElementById('q'+ qid + '_a4_ok');
    q_suggest = document.getElementById( 'q' + qid + '_suggest' );
    q_warning = document.getElementById( 'q' + qid + '_warning' );
    if( a1.checked || a2.checked || a3.checked || a4.checked )
    {   q_suggest.innerHTML = "";
        q_warning.innerHTML = "";
        a1_ok.innerHTML = "";
        a2_ok.innerHTML = "";
        a3_ok.innerHTML = "";
        a4_ok.innerHTML = "";
        if( a1.checked )
        {   a1_ok.innerHTML = "Correct";
        }
        else if( a2.checked )
        {   a2_ok.innerHTML = "Correct";
        }
        else if( a3.checked )
        {   a3_ok.innerHTML = "Correct";
        }
        else if( a4.checked )
        {   a4_ok.innerHTML = "Correct";
        }
    }
    else
    {   if( load_previous_answers )
        {   q_suggest.innerHTML = "";
            q_suggest.style.display = "none";
            q_warning.innerHTML = "Choose a correct answer";
            q_warning.style.display = "block";
        }
        else
        {   q_suggest.innerHTML = "Choose a correct answer";
            q_suggest.style.display = "block";
            q_warning.innerHTML = "";
            q_warning.style.display = "none";
        }
    }
}

function addEffectToRadio(el)
{   el.disabled = true;
}

function addEffectToInput(el)
{   el.onfocus = function()
    {   this.style.border = "1px solid #000000";
        this.select();
    }
    el.onblur = function()
    {   this.style.border = "1px solid #DDDDDD";
    }
}

function QuizForm()
{   if( !document.getElementsByTagName )
    {   return false;
    }
    var radio = getElementsByClass( "radio" );
    for( var i=0; i < radio.length; i++ )
    {   addEffectToRadio( radio[i] );
    }
    var form = document.getElementsByTagName( "input" );
    for( var i=0; i < form.length; i++ )
    {   if( form[i].type != 'submit' )
        {   addEffectToInput( form[i] );
        }
    }
    var form = document.getElementsByTagName( "textarea" );
    for( var i=0; i < form.length; i++ )
    {   addEffectToInput( form[i] );
    }
}

addLoadEvent(QuizForm);
question_count = 0;
question_count = default_question_count;

function QuizPrep()
{   for( var i = 1; i <= question_count; i++ )
    {   addSingleQuestion( i );
        updateSuggestionToTriviaQuestion( i );
    }
    if( load_previous_questions || load_previous_answers )
    {   load_previous_questions = false;
        load_previous_answers = false;
        while( question_count < min_question_count )
        {   addQuestion();
        }
        validateAnswers();
    }

    setQuestionDeleteAll( true );
    updateResultScores();
    document.getElementById( 'add-question-link' ).onclick = addQuestion;

    // Update Results with Quiz Title
    document.getElementById( 'quiz-title' ).firstChild.onkeyup = updateQuizTitle;
    document.getElementById( 'quiz-title' ).firstChild.onkeydown = updateQuizTitle;

    // Main Photo Preview
    document.getElementById( 'quiz-photo' ).firstChild.onclick = updateQuizPhoto;
    document.getElementById( 'quiz-photo' ).firstChild.onblur = updateQuizPhoto;
    document.getElementById( 'quiz-photo' ).firstChild.onfocus = updateQuizPhoto;

    // Result Photo Preview
    el = document.getElementById( 'cat1-photo' ).firstChild;
    el.onclick = function(){ updateResultPhoto( 1 ); };
    el.onblur  = function(){ updateResultPhoto( 1 ); };
    el.onfocus = function(){ updateResultPhoto( 1 ); };
    el = document.getElementById( 'cat2-photo' ).firstChild;
    el.onclick = function(){ updateResultPhoto( 2 ); };
    el.onblur  = function(){ updateResultPhoto( 2 ); };
    el.onfocus = function(){ updateResultPhoto( 2 ); };
    el = document.getElementById( 'cat3-photo' ).firstChild;
    el.onclick = function(){ updateResultPhoto( 3 ); };
    el.onblur  = function(){ updateResultPhoto( 3 ); };
    el.onfocus = function(){ updateResultPhoto( 3 ); };
    el = document.getElementById( 'cat4-photo' ).firstChild;
    el.onclick = function(){ updateResultPhoto( 4 ); };
    el.onblur  = function(){ updateResultPhoto( 4 ); };
    el.onfocus = function(){ updateResultPhoto( 4 ); };
}

addLoadEvent( QuizPrep );

