﻿
$(document).ready(function() {
 
     //Set up widget anchors to open widget
    $("a.widgetAnchor").click(function(){
        $("div#widget").removeClass("widgetClosed");
        $("div#widget").addClass("widgetExpanded");
        $("div#widgetQuestions fieldset").show();
        $("div#widgetControlPanel a").show();
        $("div#widgetControlPanel input").show();
        $("div#widgetControlPanel #buttonExpand").hide();
        pageTracker._trackEvent('Button', 'Click', 'Questions For Your Doc Start');
    });
 
    //Set up rollovers
    $("#widget input[id^=button]").hover(
        function() {
            this.src = this.src.replace("-off", "-on");
        },
        function() {
            this.src = this.src.replace("-on", "-off");
        }
    );
    $("#widget a[id^=button]").hover(
        function() {
            var background = $(this).css("background-image");
            background = background.replace("-off", "-on");
            $(this).css("background-image", background);
        },
        function() {
            var background = $(this).css("background-image");
            background = background.replace("-on", "-off");
            $(this).css("background-image", background);
        }
    );
    
    $("#buttonExpand").click(function() {
        $("div#widget").removeClass("widgetClosed");
        $("div#widget").addClass("widgetExpanded");
        $("div#widgetQuestions fieldset").show();
        $("div#widgetControlPanel a").show();
        $("div#widgetControlPanel input").show();
        $("div#widgetControlPanel #buttonExpand").hide();
        pageTracker._trackEvent('Button', 'Click', 'Questions For Your Doc Show');
        return false;
    });
    $("#buttonCollapse").click(function() {
        $("div#widget").removeClass("widgetExpanded");
        $("div#widget").addClass("widgetClosed");
        $("div#widgetQuestions fieldset").hide();
        $("div#widgetControlPanel a").hide();
        $("div#widgetControlPanel input").hide();
        $("div#widgetControlPanel #buttonExpand").show();
        return false;
    });
    $("#buttonAdd").click(function() {
        var cookieValue = $.cookie("widgetQuestions");
        if (!cookieValue) cookieValue = "";
 
        //Find checked questions and add to cookie if needed
        $("div#widgetQuestions").find("li input:checked").each(function(i) {
            var valueToAdd = this.id + "|";
        
            //Only add if cookieValue doesn't already has this ID
            if (cookieValue.indexOf(valueToAdd) == -1) {
                cookieValue += valueToAdd;
            }
        });
        
        //Find unchecked questions and remove from cookie if needed
        $("div#widgetQuestions").find("li input:not(:checked)").each(function(i) {
            var valueToRemove = this.id + "|";
            
            //If cookieValue has this ID, remove it
            if (cookieValue.indexOf(valueToRemove) != -1) {
                cookieValue = cookieValue.replace(valueToRemove, "");
            }
        });
        
        //Save to cookie
        $.cookie("widgetQuestions", cookieValue, {expires: 30} );
        
        //Update question count
        $("span.myQuestionCount").html(getCookieCount());
        return false;
    });
    $("#selectAllQuestions").click(function() {
        //Check all checkboxes
        $("ul#questionList input:checkbox").attr("checked", true);
        return false;
    });
    $("#unselectAllQuestions").click(function() {
        //Uncheck all checkboxes
        $("ul#questionList input:checkbox").attr("checked", false);
        return false;
    });
    $("#saveAndPreview").click(function() {
        var cookieValue = "";
        
        //Find checked questions
        $("ul#questionList").find("li input:checked").each(function(i) {
            cookieValue += this.id + "|";
        });
        
        //Save to cookie
        $.cookie("widgetQuestions", cookieValue, {expires: 30} );
    
        if (getCookieCount() > 0) {
            var popup = window.open("epilepsy-discussion-guide-preview.aspx", "preview", "width=630,height=700,status=yes,toolbar=no,location=no,menubar=no,scrollbars=yes");
            popup.focus();
        } else {
            alert("To view the preview, you must select at least one question.");
        }
        pageTracker._trackEvent('Button', 'Click', 'Neuro Discussion Guide Save & Preview');
        return false;
    });
    
    $(".getGuide a.getMyGuide").click(function() {
        //Clear out inputs
        $("div#outputPopup input:text").val("");
        
        //Show popup
        $("div#outputPopup").modal({closeClass: "popupClose"});
        $("#outputRight li:first-child label, #outputRight li:first-child input").click(function(){
			if($("input#survey1no").is(":checked")){
				$("#opt-question").show();
			}else{
				$("#opt-question").hide();
			}
        });
        return false;
        
    });

    //Hide survey validation errors on load
    $("div#outputRight #parent-question div.error").hide();
    $("div#outputRight #opt-question div.error").hide();
    
    //Onclick of radios
    $("div#outputRight input[name='radSurveyQ1']").click(function(event) {
        $("div#outputRight #parent-question div.error").hide();
    });
    $("div#outputRight input[name='radSurveyQ2']").click(function(event) {
        $("div#outputRight #opt-question div.error").hide();
    });
    
    //Popup submit code 
    $("body.discussionGuide div#outputPopup a.popupSubmit").click(function() {
        var outputType = $("input[@name='outputType']:checked").val();
        
        if (saveSurvey() == true) 
        {
            //Do Print or Email AJAX calls
            switch (outputType) {
                case "print":
                    $.modal.close(); 
                    window.print();
                    break;
                case "email":
                    sendEmail();
                    break;
            }
        }
        return false;
    });
    
    
    function saveSurvey() {
        var radSurveyQ1 = $("div#outputRight input[name='radSurveyQ1']:checked").val();
        var radSurveyQ2 = $("div#outputRight input[name='radSurveyQ2']:checked").val();
        
        var errorQ1 = $("div#outputRight #parent-question div.error");
        var errorQ2 = $("div#outputRight #opt-question div.error");
                
        if (typeof(radSurveyQ1) != 'undefined') {
            //'Yes' is selected to first question
            if(radSurveyQ1 == "1") 
            {
                //2nd question is unanswered 
                radSurveyQ2 = "-1";
             
                ajaxCallToHandler(radSurveyQ1, radSurveyQ2); //Valid
                
                return true;
            }
            else{
                if (typeof(radSurveyQ2) != 'undefined') { 
                    ajaxCallToHandler(radSurveyQ1, radSurveyQ2); //Valid
                    return true;
                }
                else{
                    $(errorQ2).show();//Not valid, show error for question 2
                    return false;
                }
            }
            
        } 
        else{ 
            $(errorQ1).show();//Not valid, show error for question 1
            return false;
        }
    }
    
    function ajaxCallToHandler(radSurveyQ1, radSurveyQ2)
    {
        //Call handler to save the survey    
        $.ajax({ 
            type: "GET",
            url: "/controls/handlers/SaveSurveyHandler.ashx",
            data: { "question_1": radSurveyQ1, "question_2": radSurveyQ2, "cachebuster": new Date().getTime() },
            dataType: "text",
            global: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("Error sending data: " + textStatus);
            }
        });
    }
    
    function sendEmail() {
        var valid = true;
        
        // Validate name and email
        if (!validateInput(validateName, "#popupName",
                "Please enter your name",
                "Please enter a valid name")) {
              valid = false;  
        }
        if (!validateInput(validateEmail, "#popupEmail",
                "Please enter your email address",
                "Please enter a valid email address")) {
              valid = false;  
        }
        
        if (valid) {
            var eh = new NDGEmailHandler();
            var result = eh.sendEmail({ "recipientName": $("#popupName").val(),
                                        "recipientEmail": $("#popupEmail").val()
                                      });
            if (ajaxSuccess(result)) {
                //hide the fieldset
                $("fieldset").hide();
                //show confirm message
                var message = "<h2>An email has been sent to " + $("#popupEmail").val() + "</h2>";
                $("div#confirmCopy").html(message);
                $("div#emailResult").show();
            } else {
                // There was a problem
                alert("Your request could not be completed:\n\n" + result);
            }
        }
    }
    
    //Return number of questionIDs stored in cookie
    function getCookieCount() {
        var count = 0;
        
        //Load cookie and split on |s
        var cookieValue = $.cookie("widgetQuestions");
        if (cookieValue) {
            var values = cookieValue.split("|");
            
            // For each nonempty value, increment count
            for (var i=0; i<values.length; i++) {
                if (values[i] != "") count++;
            }
        }
        return count;
    }
    //Update question count
    $("span.myQuestionCount").html(getCookieCount());
    
    //Close button on Confirm Email layer
    $("a#linkClose").click(function() {
        $.modal.close(); 
    });
    
    $("label.ndgQuestion input").click(function(event) {
        
        // Only track checks, not un-checks
        if ($(this).attr("checked")) {
        
            var questionText = $(this).siblings("span.questionText");
            if (questionText.length == 1) {
            
                questionText = $.trim(questionText.html());
                
                $.ajax({ 
                    type: "GET",
                    url: "/controls/handlers/NDGQuestionTracker.ashx",
                    data: { "questionText": questionText, "cachebuster": new Date().getTime() },
                    dataType: "text",
                    global: false,
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("Error sending data: " + textStatus);
                    }
                });
            } // if (questionText.length == 1) {
        } // if ($(this).attr("checked")) {
    });
    
});
    
