﻿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"
};

var linkPrintPage = "";   
var pageLoadPrintPage = "";  

$(document).ready(function() {
    OABQuiz.init("#wrapper");    
});

var OABQuiz = {
    score: {},
    rows: null,
    poptips: null,
    
    
    //action listeners
    init: function(rootNode){
    
       
        var self = this;
        var f_tracking = new floodlight(); 
        
        f_tracking.init();  
        
        self.rows = $(rootNode + " table#questions tr");
        self.poptips = $(rootNode + " #poptips img");
        
        // wire delegate to targets
        $(rootNode).click(jQuery.delegate({
          
          "#step1 input[type='radio']" : function(e) { 
               self.rowClick(e.target); 
          },
          
          "#step2 input[type='reset']" : function(e) { 
               sendTracking(null, "3IQ Clear all selections", "3IQ Assessment Page", null );
               self.resetSecond(); 
          },
                    
          ".quizReset" : function(e) { 
                  
              if ( $('.error_state').is(':visible')){
                      sendTracking(null, "OAB Quiz Error Clear all selections", "OAB Symptom Quiz Error", null ); 
              } 
              else {
                       sendTracking(null, "Clear all selections", "OAB Symptom Quiz Layer", null ); 
              }
              $('.error_state').fadeOut('slow',function(){$('.error_state').css("visibility","hidden").css("display","");});
                
          },
          
          "#step1 .quizNext" : function (e) {
               // sendTracking(null, "OAB Quiz Next", "OAB Symptom Quiz Layer", null);
                self.quizGoSecond(self.rows, e);   
                     
                
               // sendPageTracking("3IQ Assessment Page",null,"Toviaz Unbranded", "OAB Symptom Quiz");
                
                
                
                
          },  
            
          ".quizNext" : function(e) { 
                sendTracking(null, "Get results", "OAB Symptom Quiz Results", null);
                self.quizGoSecond(self.rows, e);   
                sendPageTracking("OAB Symptom Quiz Results",null,"Toviaz Unbranded", "OAB Symptom Quiz"); 
                 
          },
          
          ".quizSubmit":function(e){ 
                sendTracking(null, "3IQ Submit", "3IQ Assessment Page", null);
                self.showQuizResults();
                sendPageTracking("OAB Symptom Quiz Results and 3IQ Results",null,"Toviaz Unbranded", "OAB Symptom Quiz"); 
          }, 
          
          "#converseBtn" : function(e) { self.showAllPoints(e); /*trackPrintConversationStartersClick();*/ },
         
          ".print" : function(e) { e.preventDefault();  
          
          }
        }));
               
        $(".print").click (function () {
             sendTracking(null, "" + linkPrintPage +  "Print bottom",pageLoadPrintPage, null);
            // f_tracking.doTracking(1, self.printQuiz(self.rows) ); 
             self.printQuiz(self.rows);
             //trackPrintQuizClick();
           
        }); 
        
        $(".print_top").click (function () {
       
             sendTracking(null, "" + linkPrintPage +  "Print top",pageLoadPrintPage, null);
             self.printQuiz(self.rows);
          
        }); 
       
       
        
        
        // suppress real submit
        $("form").submit(function(e){
            e.preventDefault();
        }); 
        
        $(".quiz-foot .back").click (function(e){
             e.preventDefault();
             sendTracking(null, "3IQ Back", "3IQ Assessment Page", null);
             self.goBackPage();
            // sendTracking(null, "3IQ Back", "3IQ Assessment Page", null);
                                 
        }); 
        
        $(".quiz-foot .edit_answers").click(function(e){
             e.preventDefault();
             sendTracking(null, "" + linkPrintPage + "Edit Answers", pageLoadPrintPage, null);
             self.editAnswers(self.rows); 
        }); 
        
        $('#step2 .is_answering input[id^="radio_"]').click(function() {
            self.leakedChange(this);  
        }
        ); 
        
        
        
   $("div#step3 a.findOutMore").click(function(ev) {
        ev.preventDefault();
        sendTracking(null, linkPrintPage + $(this).attr("name"),pageLoadPrintPage, null);
        sendPageTracking("Interstitial Page",null,"Toviaz Unbranded", "OAB Symptom Quiz"); 
        window.parent.findOutMore( $(this).attr("href"));
       
    });
        
        
    },
    
    /*action listeners*/
    
    rowClick: function(target){
        var row, self = this;
       
        var err_msj =   $(target).parent().parent().find('.error_state'); 
        
        $(err_msj).fadeOut('fast',function(){$(err_msj).css("visibility","hidden").css("display","");});
        self.setScoreAndQuestion(target);
        
    },
    
    setScoreAndQuestion: function(target){
        this.score[target.name] = target.value;
    },
        
    quizGoSecond: function(rows, e){
        var b_question = false, self = this;
        var questions=true; 
       
        var layerName =  $(".error_state").is(':visible')? "OAB Symptom Quiz Error" : "OAB Symptom Quiz Layer";  
        var gender = $("#q1-block").find("input:radio:checked").val()>=0?true:false;  
        
        if(!gender) {
           $("#q1-block").find('.error_state').css('visibility','visible').hide().fadeIn('slow'); 
        }
                 
        $(rows).each( function(){ 
                                    
           b_question = ($(this).find("input:radio:checked").val()>=0?false:true); 
           
           if(b_question) {
                $(this).find('.error_state').css('visibility','visible').hide().fadeIn('slow'); 
                questions = false;
           }
            
        });
        
        if(questions&&gender){
            //s.sendFormEvent('s', 'OAB Symptom Quiz Layer', 'frmQuizQuestions');
            sendTracking(null, "OAB Quiz Next", "OAB Symptom Quiz Layer", null);
            self.finishfirstStep(e,rows); 
        } else {
            sendTracking(null, "OAB Quiz Error Next",layerName, null);
            sendPageTracking("OAB Symptom Quiz Error",null,"Toviaz Unbranded", "OAB Symptom Quiz"); 
           // s.sendFormEvent('e', 'OAB Symptom Quiz Layer', 'frmQuizQuestions', 'All Required Fields!');
        }
    },
    
    finishfirstStep : function (e,rows) {
     
      if ($(rows[3]).find("input:radio:checked").val() == 0 &&
          $(rows[7]).find("input:radio:checked").val() == 0)
      {
          $("#step2 .is_answering #radio_no").attr('checked', 'checked');
          $("#step3 .asses_results").css("display","none"); 
          linkPrintPage = "OAB Results ";
          pageLoadPrintPage = "OAB Symptom Quiz Results " 
          sendPageTracking("OAB Symptom Quiz Results",null,"Toviaz Unbranded", "OAB Symptom Quiz");
          this.showResults(); 
          this.goPage(2);   
          
      }else 
      {
         $("#step2 .is_answering #radio_yes").attr('checked', 'checked');
          linkPrintPage = "OAB Results ";   
          pageLoadPrintPage = "OAB Symptom Quiz Results and 3IQ Results " ;  
          this.leakedChange("#step2 .is_answering #radio_yes"); 
          sendPageTracking("3IQ Assessment Page",null,"Toviaz Unbranded", "OAB Symptom Quiz");
          this.goNextPage(); 
      }
           
     } , 
    
    resetSecond : function () {
        $("#step2 .answering input").attr('checked',false); 
    },  
    
    showQuizResults : function () {
       this.showResults();  
       this.goNextPage();  
    }, 
            
    goNextPage : function ()  {
       this.goPage(1);  
    }, 
    
    goBackPage : function ()  {
       this.goPage(-1); 
    },
    
    goPage : function (next) {
        var currentStep = $('#wrapper div[id^="step"].show').attr('id').replace("step",""); 
        var nextStep = (parseInt(currentStep))+next
        
        $("#wrapper #step"+ nextStep).addClass("show");
        $("#wrapper #step"+ nextStep).removeClass("hideElem");
        $("#wrapper #step"+ currentStep).addClass("hideElem");
        $("#wrapper #step"+ currentStep).removeClass("show");
        
        /*
        $("#wrapper #step"+ currentStep).fadeOut("fast",function(){; $("#wrapper #step"+ currentStep).removeClass("show");}); 
        $("#wrapper #step"+ nextStep).fadeIn("fast",function(){;$("#wrapper #step"+ nextStep).addClass("show");   });
        */
        
    },
    
    leakedChange : function (element) {
      
       if ($(element).attr("id")=="radio_no") {
             $("#step2 .answering").fadeOut(100,function(){ $("#step2 .noAnswering").fadeIn(100);} );
             // update variables 
            linkPrintPage = "OAB Results ";   
            pageLoadPrintPage = "OAB Symptom Quiz Results ";  

             
       }
       else {
             $("#step2 .noAnswering").fadeOut(100,function(){  $("#step2 .answering").fadeIn(100);} ); 
            linkPrintPage = "OAB and 3IQ Results ";   
            pageLoadPrintPage = "OAB Symptom Quiz Results and 3IQ Results ";  
       }
          
    }, 
    
    editAnswers : function(rows) {
       if ($(rows[3]).find("input:radio:checked").val() == 0 &&
           $(rows[7]).find("input:radio:checked").val() == 0) {
           this.goPage(-2); 
       } else {
           this.goBackPage(); 
       }
    } , 
  
    showResults: function(){
        var self = this, scoreTotal = 0;
   
        // 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);
        
        this.loadResultsOnGrid();  
        this.loadAnswers();  
        
    },
    
    loadResultsOnGrid:function() {
        var questions = $("#step3 #resultsWrapper #results").find(".question");
        var i = 0;  
                
        for (var key in this.score) 
        {
         
           if(key!="q_0" && key!="undefined") 
           {
           
             var scoreInt = parseInt(this.score[key]);  
             
             $(questions[i]).find(".d_result p").html(questionAnswerMatrix[scoreInt]); 
             
             var squares = $(questions[i]).find(".d_result span");  
                          
             $(squares).removeClass("filled"); 
             // remove all filled squares before reload them        
                 
             for (var j = 0; j < scoreInt; j++)
             {
                $(squares[j]).addClass("filled"); // OK
             }
             
             i++; 
             
           } //if
            
        } // for 
                  
    },  //loadResultsOnGrid
    
    loadAnswers:function ()  {
          
          $("#step3 ul.leaked_3_m,#step3 ul.leaked").html(""); 
    
    
          if ($("div.is_answering #radio_yes").is(":checked")) 
          {         
                $("#step3 .asses_results").css("display","block"); 
             
               $("#step3 ul.answered li").html("Yes");  
                           
               var answersL = $('#step2 .answering div.leaked input:checked'); 
               
               $(answersL).each (function(){
                   $("#step3 ul.leaked").append("<li>"+  $(this).next("label").html().replace("?",".")   +   "</li>");
               });  
               
               var answersL3 =  $('#step2 .answering div.leaked_3_m input:checked'); 
               
                $(answersL3).each (function(){
                   $("#step3 ul.leaked_3_m").append("<li>"+  $(this).next("label").html().replace("?",".")  +"</li>");
               }); 
                
          } // if 
          else 
          {
                 $("#step3 .asses_results").css("display","none"); 
                
          }
    },  
    
    showAllPoints: function(){
        $("#wrapper #talking_points div").addClass("showPoint");
        $("#converseBtn").addClass("hideElem");
        $("#wrapper #talking_points").css("height", "190px");
    },
    
    findOutMore:function () {
       
       
    
    },
    
    
 
    
    
    printQuiz: function(rows){
        var self = this;
              
        $("#step4 #result").html(""); 
        $("#step4 #result").append($("#step3 #score #currentScore").clone()); 
        // deletable remove
        
         $(".deletable").remove();  
        
        var i = 0;  
        var questions = $("#step4 #dynamic_result").find(".item");
        
       
              
         for (var key in this.score) 
         {
         
           if(key!="q_0" && key!="undefined") 
           {
           
             var scoreInt = parseInt(this.score[key]);  
             $(questions[i]).find(".fill_result p").html(questionAnswerMatrix[scoreInt]); 
                  
             for (var j = 0; j < 5; j++)
             {
                if (j<scoreInt){
                  $(questions[i]).find(".fill_result").append('<img src="images/OABQuiz/img-select-on.gif" class="deletable"/>'); 
                } 
                else {
                  $(questions[i]).find(".fill_result").append('<img src="images/OABQuiz/img-select.gif" class="deletable"/>'); 
                }
             }
             
             i++; 
             
           } //if
            
        } // for 
   
        var newcontent = $("#step3 ul.asses_results").clone(); 
        $("#step4 #assesment-results").html( newcontent ); 
        $("#step4 #assesment-results .asses_results ul li").prepend('<img src="/images/OABQuiz/img-bullet-check.gif" /> &nbsp;'); 
              
         if ($(rows[3]).find("input:radio:checked").val() == 0 &&
             $(rows[7]).find("input:radio:checked").val() == 0 ||
             $("div.is_answering #radio_no").is(":checked")) {
            
              $("#wrapper-print-quiz .print_page").html("2");             
              $("#assesment-results").hide(); 
              $(".assesment-results").hide(); 
           
              $(".box-container").css("visibility","hidden");   
              $("#to_the_doctor").css("visibility","hidden");  
              $(".to_the_doctor").css("visibility","hidden");  
              
              $("#assesment-results,.assesment-results,.box-container,#to_the_doctor,.to_the_doctor,.spacer_2").css("height","0px") ; 
            
            
            /*IE huge patch*/
            if ( $.browser.msie ) {
              $(".spacer_2").css("margin-top","-380px");
            }
                       
        } // if not answerennig 3iq
     
        window.print();
    }
};
