﻿jQuery.delegate = function(rules) {
    return function(e) {
        var target = $(e.target);
        for (var selector in rules)
            if (target.is(selector)) return rules[selector].apply(this, $.makeArray(arguments));
    }
};

jQuery.fn.reverse = function()
{
				return this.pushStack(this.get().reverse(), arguments);
};

    
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

var questionAnswerMatrix = {
    0: "Not at all",
    1: "A little bit",
    2: "Somewhat",
    3: "Quite a bit",
    4: "A great deal",
    5: "A very great deal"
};

$(document).ready(function() {
    OABQuiz.init("#wrapper");
    
    // hot patch Safari
    if($.browser.safari){
        $('body').addClass('browserSafari');
    }
});

var OABQuiz = {
    score: {},
    rows: null,
    poptips: null,
    
    init: function(rootNode){
        var self = this;
        self.rows = $(rootNode + " table tr");
        self.poptips = $(rootNode + " #poptips img");
        
        // wire delegate to targets
        $(rootNode).click(jQuery.delegate({
          "input[type='radio']" : function(e) { self.unlockRow(e.target); },
          ".quizReset" : function(e) { self.lockRows(self.rows); },
          ".quizSubmit" : function(e) { self.quizOnSubmit(self.rows, e); },
          "#converseBtn" : function(e) { self.showAllPoints(e); trackPrintConversationStartersClick(); },
          "#print-results" : function(e) { self.printQuiz(); trackPrintQuizClick(); }
        }));
        
        $(rootNode).mouseover($.delegate({
          "input[type='radio']" : function(e) { self.showTooltip(e.target); }
        }));
        
        $(rootNode).mouseout($.delegate({
          "input[type='radio']" : function(e) { self.hideToolTip(e.target); }
        }));
        
        // suppress real submit
        $("form").submit(function(e){
            e.preventDefault();
        }); 
        
        self.lockRows(self.rows);
        
        // pulse first question
        try{
            for (var i = 0; i < 3; i++) {
                $("#q1-block").animate({backgroundColor: "#FFFFFF"}, 1000).animate({backgroundColor: "#F0F7FF"}, 1000);
            };
        }
        catch(e){
            // jQuery throws some bogus error but still animate. catch it and swallow it
        }

    },
    
    // apply class and attribute to grey out controls and text
    lockRows: function(rows){
        var self = this;
        // wipe score in case of reset
        self.score = {};
        // set first highlight
        $("#q1-block").addClass("rowHighLight");
        // apply lock
        $(rows).each(
            function(){
                $(this).addClass("disabled");
                $("input", this).each(
                    function(){ $(this).attr("disabled","disabled"); }
                );
                // remove if present
                $(this).removeClass("rowHighLight");
            }
        );
    },
    
    /*  first question is not in a row, so access the first radio row by index
        next, if this row has not fired already(has a score), unlock the next row
        otherwise, the user changed a selection and we don't want to unlock next
        because it will select the 'next' with a disabled class, and unlock another row.
        if unlock proceeds, do so and set the score.
    */
    unlockRow: function(target){
        var row, self = this;
        
        $("#quiz-foot p").removeClass("quizerror");
        
        if( target.name == "q_0" ){ 
            $("#q1-block").removeClass("rowHighLight");
            row = self.rows[0]; 
            trackSymptomQuizGenderSelect(target.value=='2'?'Male':'Female');//Tracking    
        }
        else if( !self.score[target.name] ){
            row = self.rows.next(".disabled")[0]; 
            
        }
        else{self.setScoreAndQuestion(target); return; }
        
        $("input", row).each( function(){ $(this).removeAttr("disabled"); } );
        $(row).removeClass("disabled");
        $(row).prev().removeClass("rowHighLight");
        $(row).addClass("rowHighLight");
        
        self.setScoreAndQuestion(target);
    },
    
    setScoreAndQuestion: function(target){
        this.score[target.name] = target.value;
    },
    
    showTooltip: function(target){
        if( target.name == "q_0" ){ return; }
    
        var self = this;
        var pos = $(target).offset();
        var tip = self.poptips[target.value];
        var x = (pos.left - $(tip).width() ) + 47;
        var y = pos.top - $(tip).height();
        
        // hot patch IE's broken positioning
        if($.browser.msie){
        //    y = pos.top - ($(tip).height() * 3) - 5;
        }

        $(tip).css("left", x);
        $(tip).css("top", y);
        $(tip).css("visibility", "visible");
    },
    
    hideToolTip: function(target){
        var self = this;
        var tip = self.poptips[target.value];
        $(tip).css("visibility", "hidden");
    },
    
    quizOnSubmit: function(rows, e){
        var flag = false, self = this;
        $(rows).each( function(){ 
            if( $(this).hasClass("disabled") ){
                $("#quiz-foot p").addClass("quizerror");
                flag = true;
            }
        });
        
        if(!flag){
            self.showResults(); 
            trackSymptomQuizEnd();
        }
    },
    
    showResults: function(){
        var self = this, scoreTotal = 0;
        // show step 2, hide quiz
        $("#step2").addClass("showResults");
        $("#wrapper form").addClass("hideElem");
        // generate score and show points
        for(var key in self.score){
            if(self.score[key] != "0")
                $("#wrapper #talking_points ." + key).addClass("showPoint");
            // get as int
            var scoreAsInt = parseInt( self.score[key] );
            // aggregate total
            scoreTotal += scoreAsInt;
            // check if more conversations are to be shown 
            if(key != "q_0" && scoreAsInt == 0){
                 $("#converseBtn").removeClass("hideElem");
            }
        }
        // show score and global point
        $("#currentScore").text(scoreTotal);
        // $("#wrapper #talking_points .all").addClass("showPoint");
    },
    
    showAllPoints: function(){
        $("#wrapper #talking_points div").addClass("showPoint");
        $("#converseBtn").addClass("hideElem");
        $("#wrapper #talking_points").css("height", "190px");
    },
    
    printQuiz: function(){
        var self = this;
        
        // clone score copy block and insert
        $("#wrapper #step2 .inPrint").clone().insertAfter("#wrapper-print-quiz h1");
        
        // set question answer degree, offset index by one as questions start at q_1
        $("#wrapper-print-quiz .degree").each( function(i){
            $(this).text( questionAnswerMatrix[ self.score["q_" + (i + 1)] ] );
        });
        
        // get talking points and put into print container. jquery insert does nodelist backward, so we reverse it
        $("#wrapper #talking_points .showPoint").reverse().clone().insertAfter("#wrapper-print-quiz .inPrint");
        
        // format content
        $("#wrapper-print-quiz tr:first-child").addClass("indentContent");
        
        window.print();
    }
};