/**
 * @package JProQuiz
 * @author Nick Bartkowiak <nickbart@gmail.com>
 * @copyright Copyright (c) 2008, Nick Bartkowiak
 * 
 *
 * A powerful, configureable, piece of quiz software built for the web in Javascript.
 * 
 * 
 * Re-written and modified by Edward Vermillion
 * 
 * Sections marked <!-- Add/Remove movie tickets: --> will need to be modified 
 * to enable or disable the free movie tickets references in the quiz. Further
 * instructions in each applicable section.
 */

/**
 * Main quiz engine.
 */

var Quiz = function (file, multifile) {
    
    this.questionsFile = file;
    
    this.multiFile = multifile;
    
    this.preload = ['images/multiQuestionImage.jpg', 
                    'images/proceedbutton.jpg',
                    'images/qheader_1.jpg',
                    'images/qheader_2.jpg',
                    'images/qheader_3.jpg',
                    'images/qheader_4.jpg',
                    'images/qheader_5.jpg',
                    'images/qheader_6.jpg',
                    'images/qheader_7.jpg',
                    'images/qheader_8.jpg',
                    'images/qheader_9.jpg',
                    'images/qheader_10.jpg',
                    'images/quizQuestionBG.jpg'];
                    
    this.currStory = TMI.getStory();
    
    if (this.currStory == null) {
        this.currStory = 'kerri';
    }
    
    switch (this.currStory) {
        case 'kerri':
            this.quizIntroBG = 'quizIntroBGKerri.jpg',
            this.quizGratsBG = 'gratsBGKerri.jpg'
            break;
        case 'marcus': 
            this.quizIntroBG = 'quizIntroBGMarcus.jpg',
            this.quizGratsBG = 'gratsBGMarcus.jpg'
            break;
        case 'gina': 
            this.quizIntroBG = 'quizIntroBGGina.jpg',
            this.quizGratsBG = 'gratsBGGina.jpg'
            break;
    }
    
    $('mainct').style.background = "transparent url('images/" + this.quizIntroBG + "') no-repeat top left";
    
    document.imgs = [];
    for (var i=0; i < this.preload.length; i++) {
        document.imgs[i] = new Image();
        document.imgs[i].src = this.preload[i];
    }
    document.imgs[i] = new Image();
    document.imgs[i].src = 'images/' + this.quizGratsBG;
    
    var _this = this;
    
    new Ajax.Request(this.questionsFile, {
        
            method: 'get',
            onComplete: function(successQuestions) {
                
              var questionStrng = successQuestions.responseText.replace(/[\r\n\t]+/g, "");
              
              _this.questions = eval('(' + questionStrng + ')');
            }
        }
    );
    
    new Ajax.Request(this.multiFile, {
        
            method: 'get',
            onSuccess: function(successMulti) {
                
              var multiString = successMulti.responseText.replace(/[\r\n\t]+/g, "");
              
              _this.multijson = eval('(' + multiString + ')');
            }
        }
    );
};

Quiz.prototype = {
    
    currStory: '',
    
    storyData: {},
    
    quizIntroBG: '',
    quizGratsBG: '',
    
    questionsFile: '',
    questions: [],
    
    multiFile: '',
    multijson: [],
    numMulti: 0,
    
    currentQuestion: 0,
    
    userFirstName: '',
    
    userLastName: '',
    
    userID: '',
    
    certWindow: false,
    
    preload: [],
    
    start: function () {
        
        if (this.setUserFirstName()) {
        
            var question = this.getNextQuestion();

            $('mainct').style.background = "transparent url('images/quizQuestionBG.jpg') no-repeat top left";
            
            $('ppLink').style.display = 'none';
            
            if (question) {
            
                this.displayQuestion(question, false);
                $('qheader').style.display = 'block';
            }
        }
        
        // debuging/testing - straight to grats, no quiz
//        if (this.setUserFirstName()) {
//            this.showGrats();
//        }
    },
    
    setUserFirstName: function () {
        
        this.userFirstName = $F('firstname');
        
        if (this.userFirstName.blank()) {
            alert('Please Enter Your First Name To Begin');
            $('firstname').focus();
            return false;
        }
        return true;
    },
    
    getNextQuestion: function () {
        
        if (this.currentQuestion == this.questions.size()) {
            
            this.showMultiSelect(false);
            return false;
            
        } else {
            
            // If it was not the last question, move on the next question.
            return this.questions[this.currentQuestion];
        }
    },
    
    displayQuestion: function (question, showFYI, correct) {
        
        var listNodes = [];
        
        question.options.each(function(o,i) {
            
                listNodes.push(Builder.node('li', 
                        {
                            className: 'option_item',
                            id: o.id
                        },
                        [ Builder.node('a', { href: 'javascript:void(0)' }, [Builder.node('span', { className: 'boldred' }, o.id + '.'), ' ' + o.text]) ]
                    )
                )
            }
        );
        
        var questionContainer = Builder.node('div', { className: 'question' },            
            [
                Builder.node('p', question.text),
                Builder.node('ul', { className: 'options_list' }, listNodes),
            ]
        );
        
        $('main_panel').update(questionContainer);
        
        $$('li.option_item').each(function(o)
            {   
                var answer = o.identify();
                o.observe('click', function(){ quiz.answer(answer, question) });
            }
        );
        
        if (showFYI) {
            
            var encouragementText = '';
            var fyiText = '';
            
            if (correct) {
                encouragementText = "Great " + this.userFirstName + "! That's Correct!";
                $('proceedbutton').style.display = 'block';
            } else {
                encouragementText = "Sorry " + this.userFirstName + ", that's not correct. Read the passage below and try again.";
            }
            
            fyiText = "<div class='boldred'>" + encouragementText + "</div><div><span class='boldred'>FYI: </span>" + question.fyi + "</div>";
        
            $('fyi').update(fyiText);
            $('fyi').style.display = 'block';
            
        }
    },
    
    answer: function (answer, question) {
        
        if (question.answer == answer) {
            
            this.displayQuestion(question, true, true);
            
        } else {
            
            this.displayQuestion(question, true, false);
        }
    },
    
    proceed: function () {
        
        $('fyi').style.display = 'none';
        $('fyi').update('');
        $('proceedbutton').style.display = 'none';
        
        this.currentQuestion = this.currentQuestion + 1;
        
        var question = this.getNextQuestion();
        
        if (question) {
            this.displayQuestion(question, false);
            var qheaderNum = this.currentQuestion + 1;
            $('qheader').style.background = 'url(images/qheader_' + qheaderNum + '.jpg) no-repeat top left';
        }
    },
    
    showMultiSelect: function (end) {
        
        $('fyi').style.display = 'none';
        $('fyi').update('');
        
        var qheaderNum = this.currentQuestion + 1;
        $('qheader').style.background = 'url(images/qheader_' + qheaderNum + '.jpg) no-repeat top left';
        $('scroller').style.marginLeft = '10px';
        
        var content =  [];
        var multianswers = [];
        
        content.push(Builder.node('img', { src: 'images/multiQuestionImage.jpg', 
                                           width: '357',
                                           height: '271',
                                           id: 'multiQuestionImage' }));
        
        if (!end) {
            multianswers.push(Builder.node('div', { id: 'multitop' },
                                           [ Builder.node('div', 'Find the hazards in the picture.'),
                                             Builder.node('span', { className: 'hint' }, 
                                                          [ 'Select', Builder.node('span', { className: 'boldred' },' four '), 'from the list below'])
                                           ]));
        }
        
        var listClass = 'multili';
        var endText = 'Correct answers will be highlighted in green.';
        
        if (end) {
            
            listClass = 'multiliend';
            
            $('proceedbutton').style.display = 'block';
            
            Event.stopObserving('proceed', 'click');
            
            $('proceed').observe('click', function(){ quiz.showGrats() });
            
            endText = "Actually, they're all correct!";
        }
        
        for (var i=0; i < this.multijson.length; i++) {
            
            var listEls = [];
            
            var divID = this.multijson[i].id;
            var header = this.multijson[i].header;
            
            this.multijson[i].options.each(function(o,i) {
            
                    listEls.push(Builder.node('li', 
                                              { className: listClass, id: o.id },
                                              [ quiz.buildMultiList(o.text, end) ]
                        )
                    )
                }
            );
            
            multianswers.push(Builder.node('div', 
                                           { id: divID }, 
                                           [ Builder.node('div', { className: 'multiListHeader' }, header),
                                             Builder.node('ul', { className: 'multiList' }, listEls)
                                           ])
                             );
        }
        
        multianswers.push(Builder.node('div', { id: 'multiEndText' }, endText));
        
        content.push(Builder.node('div', { id: 'multiQuestionText'}, multianswers));
        
        $('main_panel').update(Builder.node('div', content));
        
        $$('li.multili').each(function(o)
            {   
                o.observe('click', function(){ quiz.trackMulti(o) });
            }
        );
    },
    
    buildMultiList: function (text, end) {
        
        if (end) {
            
            return Builder.node('span', text);
            
        } else {
            
            return Builder.node('a', { href: 'javascript:void(0)' }, text);
        }
    },
    
    trackMulti: function (el) {
        
        this.numMulti = this.numMulti + 1;
        
        $(el).className = 'multiliend';
        
        if (this.numMulti == 4) {
            this.showMultiSelect(true);
        }
    },
    
    showGrats: function () {
        
        $('main_panel').update('');
        
        $('mainct').style.background = "transparent url('images/" + this.quizGratsBG + "') no-repeat top left";
        
        $('proceed').style.display = 'none';
        $('qheader').style.display = 'none';
        $('ppLink').style.display = 'block';
        
        var content = [];
        
        var gratsHeader = Builder.node('div', 
                                     { id: 'gratsHeader' },
                                     [ Builder.node('img',
                                                    { src: 'images/headers/gratsHeader.png',
                                                      width: '314',
                                                      height: '57' })
                                     ]);
                                     
        var gratsText = Builder.node('div', { id: 'gratsText' }, 
                                     [ 'You have successfully completed the Workplace Safety Quiz! ',
                                        // <!-- Add/Remove movie tickets: -->
                                        // comment the following to remove tickets, uncomment to add
//                                       'Fill out and submit the form below to have your free movie pass ',
//                                       'mailed to you. Your free movie pass should arrive in your mailbox ',
//                                       'in a couple of weeks. When the form is submitted you will also be ',
//                                       'able to print out a Certificate of Completion to keep for your records.'
                                       // end comment to remove
                                       
                                       // <!-- Add/Remove movie tickets: -->
                                       // comment the following to add tickets, uncomment to remove
                                       'Fill out and submit the form below for your Certificate of Completion ',
                                       'which you can print out and keep for youor records'
                                       // end comment to add
                                     ]);
        
        var gratsForm = Builder.node('div', { id: 'quizForm' }, 
                      [ Builder.node('form', { name: 'contactform',
                                               id: 'contactform', 
                                               action: 'processContact.php', 
                                               method: 'post', 
                                               onsubmit: 'return quiz.submitContactForm()' },
                                       
                                     [ Builder.node('input', { type: 'text', 
                                                               className: 'textinput',
                                                               size: '15',
                                                               name: 'firstname',
                                                               id: 'firstname',
                                                               value: 'First Name',
                                                               tabindex: '1'}),
                                                               
                                       Builder.node('input', { type: 'text', 
                                                               className: 'textinput',
                                                               size: '20',
                                                               name: 'lastname',
                                                               id: 'lastname',
                                                               value: 'Last Name',
                                                               tabindex: '2'}),
                                      // <!-- Add/Remove movie tickets: -->
                                      // comment the following to remove tickets, uncomment to add
//                                       Builder.node('input', { type: 'text', 
//                                                               className: 'textinput',
//                                                               size: '3',
//                                                               name: 'age',
//                                                               id: 'age',
//                                                               value: 'Age',
//                                                               tabindex: '3'}), 
//                                       Builder.node('br'),
//                                                               
//                                       Builder.node('input', { type: 'text', 
//                                                               className: 'textinput',
//                                                               size: '15',
//                                                               name: 'address',
//                                                               id: 'address',
//                                                               value: 'Address',
//                                                               tabindex: '4'}),
//                                                               
//                                       Builder.node('input', { type: 'text', 
//                                                               className: 'textinput',
//                                                               size: '10',
//                                                               name: 'city',
//                                                               id: 'city',
//                                                               value: 'City',
//                                                               tabindex: '5'}),
//                                                               
//                                       Builder.node('input', { type: 'text', 
//                                                               className: 'textinput',
//                                                               disabled: 'true',
//                                                               size: '3',
//                                                               name: 'state',
//                                                               id: 'state',
//                                                               value: 'TX',
//                                                               tabindex: '6'}),
//                                                               
//                                       Builder.node('input', { type: 'text', 
//                                                               className: 'textinput',
//                                                               size: '7',
//                                                               name: 'zip',
//                                                               id: 'zip',
//                                                               value: 'Zip',
//                                                               tabindex: '7'}), 
//                                       Builder.node('br'),
//                                                               
//                                       Builder.node('input', { type: 'text', 
//                                                               className: 'textinput',
//                                                               size: '20',
//                                                               name: 'email',
//                                                               id: 'email',
//                                                               value: 'Email',
//                                                               tabindex: '8'}), 
                                      // end comment to remove
                                      
                                       Builder.node('div', { id: 'gratsSubmit' },
                                                    [ Builder.node('input', { type: 'submit', 
                                                                              name: 'submit',
                                                                              id: 'submit',
                                                                              value: 'Submit Form',
                                                                              tabindex: '9'})
                                                    ])
                                       ])
                      ]);
        
          
        var gratsContent = Builder.node('div', { id: 'gratsContent' }, [ gratsHeader, gratsText, gratsForm ]);

        $('main_panel').update(gratsContent);
        
        $$('input.textinput').each(function(o)
            {   
                o.observe('focus', function(){ 
                    this.activate();
                    this.style.color = '#000000';
                });
            }
        );
        
        $('firstname').value = this.userFirstName;
        $('firstname').focus();
        
    },
    
    submitContactForm: function () {
        
        // First Name...
        if ($F('firstname').blank()) {
            $('firstname').focus();
            alert('Please enter your first name');
            return false;
        }
        this.userFirstName = $F('firstname'); 
        
        // Last Name...
        if ($F('lastname').blank() || $F('lastname') == 'Last Name') {
            $('lastname').focus();
            alert('Please enter your last name');
            return false;
        }
        this.userLastName = $F('lastname');
        
        // <!-- Add/Remove movie tickets: -->
        // comment the following to remove tickets, uncomment to add
        
//        // Age...
//        if ($F('age').blank() || $F('age') == 'Age') {
//            $('age').focus();
//            alert('Please enter your age');
//            return false;
//        }
//        var userAge = $F('age');
//        
//        // Address...
//        if ($F('address').blank() || $F('address') == 'Address') {
//            $('address').focus();
//            alert('Please enter your street address');
//            return false;
//        }
//        var userAddress = $F('address');
//        
//        // City...
//        if ($F('city').blank() || $F('city') == 'City') {
//            $('city').focus();
//            alert('Please enter your city');
//            return false;
//        }
//        var userCity = $F('city');
//        
//        // State...
//        if ($F('state') !== 'TX') {
//            $('state').focus();
//            alert('We are only able to mail movie passes to Texas State residents');
//            return false;
//        }
//        var userState = 'TX';
//        
//        // Zip...
//        if ($F('zip').blank() || $F('zip') == 'Zip') {
//            $('zip').focus();
//            alert('Please enter your zip code');
//            return false;
//        }
//        var userZip = $F('zip');
//        
//        // Email...
//        if ($F('email').blank() || $F('email') == 'Email') {
//            $('email').focus();
//            alert('Please enter your email address.');
//            return false;
//        }
//        var UserEmail = $F('email');

        // end comment to remove
        
        $('contactform').request({
            onSuccess: function (transport) { quiz.processContactResponse(transport); },
            onFailure: function () { alert('Form submission failed due to server/network error. Please try again in a few minutes.'); }
        });
        
        return false;
    },
    
    processContactResponse: function (response) {
        
        if (response.responseText == "OK") {
            
            var certLink = Builder.node('a', { href: 'javascript:void(0);', id: 'certLink' }, 'Show Certificate' );
            
            $('quizForm').update(certLink);
            
            $('certLink').observe('click', function () { quiz.showCertificate(false); });
            
            this.showCertificate(true);
        
        } else {
        
            alert(response.responseText);
        }
    },
    
    showCertificate: function (firsttime) {
        
        if (firsttime) {
            
            $('mainbg').style.display = 'none';
            $('certificate').style.display = 'block';
            
            var certFrame = Builder.node('iframe', {
                id: 'certFrame',
                name: 'certFrame',
                src: 'printCert.html',
                frameborder: '0',
                width: '612',
                height: '792'
            });
            
            $('certificate').style.width = '612px';
            $('certificate').style.height = '792px';
            $('certificate').update(certFrame);
            
        } else {
            
            $('certificate').style.display = 'block';
            $('mainbg').style.display = 'none';
        }
        
    },
    
    printCertificate: function () {
        
        $('certificate').style.display = 'none';
        $('mainbg').style.display = 'block';
    },
    
    getName: function () {
        return this.userFirstName + ' ' + this.userLastName;
    }
    
}; // End Quiz.prototype
