﻿//global close path variable..
var survCloseButtonPath = ""

//Object to manage a given survey question...
function SurveyQuestion() {
    //constants
    this.UI_TYPE_RADIO = 4
    this.UI_TYPE_CHECKBOX = 2
    //properties
    this.resultDetailID = null;
    this.questionID = null;
    this.revisionQuestionID = null;
    this.uiType = null
    this.images = new Array();
    this.lockstate = null;
    this.fieldID = "";
    this.dependentOnID = 0;

    //methods
    //Gets the ID of the container of this question.
    this.getContainerID = function(psPrefix) { return psPrefix + '_' + this.revisionQuestionID }
    //Gets the value of the field...
    this.getValue = function() {
        try {
            var value = ""
            if (this.uiType == this.UI_TYPE_RADIO)
                value = getSelectedRadio(document.getElementsByName(this.getFieldNameFromID()));
            else if (this.uiType == this.UI_TYPE_CHECKBOX)
                value = this.getCheckboxVal();
            else
                value = document.getElementById(this.fieldID).value;

            if (encodeURIComponent)
                return encodeURIComponent(String(value))
            else
                return escape(String(value))
        } catch (ex) { alert("Error in GetValue: " + ex.message) }
    }
    //Converts a field name to a field ID
    this.getFieldNameFromID = function() {
        var arrParts = this.fieldID.split("_")
        var temp = arrParts[0]
        var partCount = 0
        //last part of ID never has its underscore separator replaced in survey questions.
        for (partCount = 1; partCount < arrParts.length - 1; partCount++)
            temp = temp + '$' + arrParts[partCount];
        temp = temp + '_' + arrParts[partCount];
        return temp
    }
    //gets value from checkbox based on whether the current question is a boolean...
    this.getCheckboxVal = function() {
        try {
            var field = document.getElementById(this.fieldID);            
            if (field && field.tagName.toLowerCase() == 'input') {            
                //field (element) exists
                if (field.checked)
                    return field.parentNode.getAttribute("tval");
                else
                    return field.parentNode.getAttribute("fval");
            } else {
                return getSelectedCheckboxValue(document.getElementsByName(this.getFieldNameFromID()));
            }
        } catch (ex) { alert("Error in GetCheckboxVal: " + ex.message) }
    }
    //Sets whether the question field is enabled or disabled.
    this.setEnabled = function(psPrefix, pbDisable) {
        var fieldCount = 0
        var arrInputs = null
        //Get the wrapper div
        var wrapper = document.getElementById(psPrefix + '_' + this.revisionQuestionID);

        //If the wrapper div is found, find its contents
        if (typeof wrapper != 'undefined') {
            arrInputs = wrapper.getElementsByTagName("input");
            for (fieldCount = 0; fieldCount < arrInputs.length; fieldCount++) {
                if (pbDisable) {
                    this.lockstate = arrInputs[fieldCount].disabled;
                    arrInputs[fieldCount].disabled = pbDisable;
                } else {
                    if (!this.lockstate)
                        arrInputs[fieldCount].disabled = pbDisable
                }
            }
            arrInputs = wrapper.getElementsByTagName("select");
            for (fieldCount = 0; fieldCount < arrInputs.length; fieldCount++) {
                if (pbDisable) {
                    this.lockstate = arrInputs[fieldCount].disabled;
                    arrInputs[fieldCount].disabled = pbDisable;
                } else {
                    if (!this.lockstate)
                        arrInputs[fieldCount].disabled = pbDisable
                }
            }
        }
    }
}

//Object to manage a given Survey...
function Survey() {
    //global values
    this.survey_request = null;
    this.question_request = null
    this.containerPrefix = ""
    this.buttons = null;
    this.questionLockState = null;
    this.pleaseWaitID = "";
    this.countQuestions = null;
    this.surveyPanelID = "";
    this.updatePreview = function(surveyID) { };
    this.closeButtonPath = "";
    this.productID = "";
    this.ajaxPage = "/AJAX.aspx";
    this.surveyID = null;
    this.surveyResultHeaderID = null;
    this.questions = new Array();
    this.surveyType = 0;
    this.clientClass = 0;
    this.setSkin = false;
    this.resultListFieldID = '';
    this.resultListField = null;

    //methods
    //Fills in the required properties for a survey object
    this.configNew = function(psPrefix, parrButtons, psWaitID, psPanelID, psClosePath, poUpdatePreview, plProductID, plSurveyID, plResultID, poCountQuestions, piSurveyType, plClientClass, psResultListID) {
        this.containerPrefix = psPrefix;
        this.buttons = parrButtons;
        this.pleaseWaitID = psWaitID;
        this.surveyPanelID = psPanelID;
        this.updatePreview = poUpdatePreview;
        this.closeButtonPath = psClosePath;
        this.productID = plProductID;
        this.surveyID = plSurveyID;
        this.surveyResultHeaderID = plResultID
        this.countQuestions = poCountQuestions;
        this.surveyType = piSurveyType;
        this.clientClass = plClientClass;
        this.resultListFieldID = psResultListID;
    }
    //Adds a question at the specified index to the object
    this.addQuestion = function(idx, plResultDetailID, plQuestionID, plRevQuestionID, plUIType, psFieldID, plDependencyID) {
        this.questions[idx] = new SurveyQuestion();
        this.questions[idx].resultDetailID = plResultDetailID;
        this.questions[idx].questionID = plQuestionID;
        this.questions[idx].revisionQuestionID = plRevQuestionID;
        this.questions[idx].uiType = plUIType;
        this.questions[idx].fieldID = psFieldID;
        this.questions[idx].dependentOnID = plDependencyID;
    }
    //handles any errors detected in a function call
    this.handleError = function(psNom, ex, pbUnlockFields, pbKillRequests) {
        try {
            //display the error message
            alert("Error in " + psNom + ": " + ex.message);
            //unlock the survey...
            if (pbUnlockFields) {
                this.setSurveyEnabled(false);
                this.setPleaseWait(false);
            }
            //Kill any outstanding http request objects
            if (pbKillRequests) {
                this.survey_request = null;
                this.question_request = null
            }
        } catch (ex) {alert("Error in handleError: " + ex.message) }
    }
    //calls the UpdatePreview function -- if it exists
    this.callUpdatePreview = function() {
        if (typeof (this.updatePreview) == 'function')
            try {
                this.updatePreview.call(this, this.surveyResultHeaderID)
            } catch (e) { alert("Call to updatePreview Failed: " + e.message); }
    }
    this.callCountQuestions = function() {
        if (typeof (this.countQuestions) == 'function')
            try {
                this.countQuestions.call(this)
            } catch (e) { alert("Call to CountQuestions Failed: " + e.message); }
    }
    //turns on/off the Please Wait message
    this.setPleaseWait = function(pbShow) {
        try {
            if (typeof document.getElementById(this.pleaseWaitID) != 'undefined' && typeof ShowPleaseWait == 'function')
                if (pbShow)
                ShowPleaseWait(this.pleaseWaitID);
            else
                HidePleaseWait(this.pleaseWaitID);
        } catch (err) { alert("Error in setPleaseWait: " + err.message); }
    }
    //Enables/disables all fields in the current survey -- used to lock while updating.
    this.setSurveyEnabled = function(pbDisable) {
        try {
            var intCount = 0
            //disable questions
            for (intCount = 0; intCount < this.questions.length; intCount++)
                this.questions[intCount].setEnabled(this.containerPrefix, pbDisable);
            //disable buttons
            if(this.buttons)
                for (intCount = 0; intCount < this.buttons.length; intCount++)
                    if (document.getElementById(this.buttons[intCount]))
                        document.getElementById(this.buttons[intCount]).disabled = pbDisable;
        } catch (ex) { alert("Error in SetSurveyEnabled: " + ex.message) }
    }
    //Sets the internal HTTP request object in this function to a new HTTP request.
    this.spawnHttpRequestObject = function() {
        var req = null
        //spawn the HTTPRequest object
        if (window.XMLHttpRequest) {
            //IE 7+, FF, Chrome, Safari, Opera
            req = new XMLHttpRequest()
            if (req.overrideMimeType)
                req.overrideMimeType('text/xml');
        } else if (window.ActiveXObject) {
            //IE6
            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (ex) {
                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (ex) { }
            }
        }
        return req;
    }
    //Creates the set of survey results
    this.createSurvey = function(piQuestionIndex) {
        try {
            var params = "fn=CreateSurveyResults&IsCompass=True"
            params = params + "&SurveyID=" + String(this.surveyID) + "&ProductID=" + String(this.productID)
            params = params + "&type=" + String(this.surveyType) + "&clientclassid=" + String(this.clientClass)

            //spawn the HTTPRequest object
            this.survey_request = this.spawnHttpRequestObject()

            //Check for XMLHTTP creation and kick out if bad
            if (!this.survey_request) { alert("Error in CreateSurvey: Cannot create XMLHTTP instance."); return false; }

            //start the http request
            var fnUpdateWrapper = function(s, q) { return function() { s.updateSurveyID(q); } }
            this.survey_request.onreadystatechange = fnUpdateWrapper(this, piQuestionIndex);

            //send the request
            this.survey_request.open('POST', this.ajaxPage + '?' + params, true);
            this.survey_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            this.survey_request.setRequestHeader("Content-length", params.length);
            this.survey_request.setRequestHeader("Connection", "close");
            this.survey_request.send(params);        
        } catch (ex) { this.handleError('UpdateQuestionValue', ex, true, false); }
    }
    //Grabs the generated result ID, sticks it into the object, and then updates the question
    this.updateSurveyID = function(piQuestionIndex) {
        try {
            var surveyResultID = 0
            var intQCount = 0
            if (this.survey_request.readyState == 4) {
                if (this.survey_request.status == 200) {
                    if (window.XMLHttpRequest) {
                        //IE7+, FF, Chrome, Safari, Opera
                        var xmldoc = this.survey_request.responseXML;
                        if (xmldoc.getElementsByTagName("survey").length > 0) {
                            surveyResultID = xmldoc.getElementsByTagName("survey")[0].attributes[0].value;
                            //Get the Questions
                            var arrQuestions = xmldoc.getElementsByTagName("question");
                            for (intQCount = 0; intQCount < arrQuestions.length; intQCount++) {
                                this.questions[intQCount].resultDetailID = arrQuestions[intQCount].attributes[1].value;
                            }
                        }
                    } else if (window.ActiveXObject) {
                        //IE6
                        var result = this.survey_request.responseText;
                        var xmldoc = new ActiveXObject("Microsoft.XMLDOM")
                        xmldoc.async = "false"
                        xmldoc.loadXML(result)
                        if (xmldoc.getElementsByTagName("survey").length > 0) {
                            surveyResultID = xmldoc.getElementsByTagName("survey")[0].attributes(0).value;
                            //Get the Questions
                            var arrQuestions = xmldoc.getElementsByTagName("question");
                            for (intQCount = 0; intQCount < arrQuestions.length; intQCount++) {
                                this.questions[intQCount].resultDetailID = arrQuestions[intQCount].attributes(1).value;
                            }
                        }
                    }
                    //If we have a survey ID, continue...
                    if (surveyResultID > 0) {
                        //set the object's survey result ID
                        this.surveyResultHeaderID = surveyResultID
                        this.updateFieldValues()
                        //now, finally, update the question value.
                        this.updateQuestionValue(piQuestionIndex)
                    } else {
                        //Survey couldn't be created.
                        alert("Survey result could not be created.")

                        //unlock the survey...
                        this.setSurveyEnabled(false);
                        this.setPleaseWait(false);
                    }
                    //nuke the closure to release memory
                    this.survey_request = null;
                } else {
                    alert("Error in creating survey.  Status is " + this.survey_request.status);
                    //nuke the closure to release memory
                    this.survey_request = null;
                }
            }
        } catch (ex) { this.handleError('UpdateSurveyID', ex, true, true) }
    }
    //updates the results list....
    this.updateFieldValues = function() {
        try {
            if (!this.resultListField) { this.resultListField = document.getElementById(this.resultListFieldID); }
            var reValue = new RegExp(this.surveyID + "\\|\\d+");
            this.resultListField.value = this.resultListField.value.replace(reValue, this.surveyID + '|' + this.surveyResultHeaderID)
        } catch (ex) { this.handleError('UpdateFieldValues', ex, false, false); }
    }
    //Updates the value of a survey question
    this.updateQuestionValue = function(piQuestionIndex) {
        try {
            var params = "function=SetSurveyResultQuestionAnswerValue&IsCompass=True&"
            params = params + "SurveyResultsID=" + this.surveyResultHeaderID
            params = params + "&SurveyResultDetailID=" + this.questions[piQuestionIndex].resultDetailID
            params = params + "&AnswerText=" + this.questions[piQuestionIndex].getValue();
            //spawn the HTTPRequest object
            this.question_request = this.spawnHttpRequestObject()

            //Check for XMLHTTP creation and kick out if bad
            if (!this.question_request) { alert("Error in UpdateQuestionValue: Cannot create XMLHTTP instance."); return false; }

            //start the http request
            var fnUpdateWrapper = function(s) { return function() { s.parseQuestionVisibility(); } }
            this.question_request.onreadystatechange = fnUpdateWrapper(this);

            //send the request
            this.question_request.open('POST', this.ajaxPage + '?' + params, true);
            this.question_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            this.question_request.setRequestHeader("Content-length", params.length);
            this.question_request.setRequestHeader("Connection", "close");
            this.question_request.send(params);
        } catch (ex) { this.handleError('UpdateQuestionValue', ex, true, true); }
    }
    this.setQuestionGroupVisible = function(questionElement, enabled, piQuestionIndex) {
        try {
            var parentNode = questionElement.parentNode;
            var skinNode = null;
            var className = 'QuestionGroup' + this.questions[piQuestionIndex].dependentOnID;
            if (parentNode.parentNode.tagName.toLowerCase() == 'td') {
                skinNode = parentNode.parentNode.parentNode.parentNode.parentNode;
            } else {
                skinNode = parentNode;
            }
            if (skinNode.className == className) {
                if (enabled) { skinNode.style.display = ''; } else { skinNode.style.display = 'none'; }
            }
        } catch (ex) { this.handleError('UpdateQuestionValue', ex, true, true); }
    }
    //Takes the XMLHTTP object's response and parses it into question visibilities.
    this.parseQuestionVisibility = function() {
        var intCount = 0;
        if (this.question_request.readyState == 4) {
            if (this.question_request.status == 200) {
                if (window.XMLHttpRequest) {
                    var xmldoc = this.question_request.responseXML;
                    var questions = xmldoc.getElementsByTagName('QuestionVisibility');
                    for (intCount = 0; intCount < questions.length; intCount++) {
                        var QuestionID = questions[intCount].attributes[0].value;
                        var QuestionEnabled = questions[intCount].firstChild.nodeValue;
                        var questionElement = document.getElementById(this.containerPrefix + '_' + QuestionID);
                        if (questionElement) {
                            if (QuestionEnabled == 'true') {
                                questionElement.style.display = '';
                                this.setQuestionGroupVisible(questionElement, true, intCount)
                            } else {
                                questionElement.style.display = 'none';
                                this.setQuestionGroupVisible(questionElement, false, intCount)
                            }
                        }
                    }
                } else if (window.ActiveXObject) {
                    var result = this.question_request.responseText;
                    var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
                    xmldoc.async = "false";
                    xmldoc.loadXML(result);
                    var questions = xmldoc.getElementsByTagName("QuestionVisibility");
                    for (intCount = 0; intCount < questions.length; intCount++) {
                        var QuestionID = questions[intCount].attributes(0).value;
                        var QuestionEnabled = questions[intCount].firstChild.nodeValue;
                        var questionElement = document.getElementById(this.containerPrefix + '_' + QuestionID);
                        if (questionElement) {
                            if (QuestionEnabled == 'true') {
                                questionElement.style.display = '';
                                if (questionElement.parentNode.getAttribute('class') == 'QuestionGroup')
                                    questionElement.parentNode.style.display = '';
                            } else {
                                questionElement.style.display = 'none';
                                questionElement.style.display = 'none';
                                if (questionElement.parentNode.getAttribute('class') == 'QuestionGroup')
                                    questionElement.parentNode.style.display = 'none';
                            }
                        }
                    }
                }
            } else { alert("Error in processing survey update.  Status is " + this.question_request.status); }

            try {
                //unlock the survey...
                this.setSurveyEnabled(false);

                //Reset visible area
                ShowSurveyPopup(this.surveyPanelID)

                //update answered question status
                this.callCountQuestions()
                //Update any configured previews
                this.callUpdatePreview()
                //Hide the Please Wait message
                this.setPleaseWait(false);
                //Nuke the closure to free memory
                this.question_request = null;
            } catch (ex) { alert('Error in question update cleanup:' + ex.message) }
        }
    }
    //This is the function that gets called when a question value changes.
    this.answerChangeHandler = function(piQuestionIndex) {
        try {
            //lock down the survey so it can't be modified while updating
            this.setSurveyEnabled(true);
            this.setPleaseWait(true);
            //start updating
            if (this.surveyResultHeaderID == 0) {
                //No survey ID.  Must create a results set before updating the value
                this.createSurvey(piQuestionIndex);                
            } else {
                //Just update the value...
                this.updateQuestionValue(piQuestionIndex);
            }
        } catch (err) {
            alert("Error in UpdateQuestionValue: " + err.message);
            //unlock the survey...
            this.setSurveyEnabled(false);
            this.setPleaseWait(false);
        }
    }

}



//Non-object utility functions

// returns the array number of the selected radio button or -1 if no button is selected
function getSelectedRadio(buttonGroup) {
    if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
        for (var i = 0; i < buttonGroup.length; i++) {
            if (buttonGroup[i].checked) {
                //alert(buttonGroup[i].value);
                return buttonGroup[i].value;
            }
        }
    } else {
        if (buttonGroup.checked) {
            return 0;
            buttonGroup[0].value;
        } // if the one button is checked, return zero
    }
    // if we get to this point, no radio button is selected
    return -1;
}

// Go through all the check boxes. return an array of all the ones
// that are selected (their position numbers). if no boxes were checked,
// returned array will be empty (length will be zero)
function getSelectedCheckbox(buttonGroup) {
    var retArr = new Array();
    var lastElement = 0;
    if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
        for (var i = 0; i < buttonGroup.length; i++) {
            if (buttonGroup[i].checked) {
                retArr.length = lastElement;
                retArr[lastElement] = i;
                lastElement++;
            }
        }
    } else { // There is only one check box (it's not an array)
        if (buttonGroup.checked) { // if the one check box is checked
            retArr.length = lastElement;
            retArr[lastElement] = 0; // return zero as the only array value
        }
    }
    return retArr;
}

// return an array of values selected in the check box group. if no boxes
// were checked, returned array will be empty (length will be zero)
function getSelectedCheckboxValue(buttonGroup) {
    var retArr = new Array(); // set up empty array for the return values
    var selectedItems = getSelectedCheckbox(buttonGroup);
    if (selectedItems.length != 0) { // if there was something selected
        retArr.length = selectedItems.length;
        for (var i = 0; i < selectedItems.length; i++) {
            if (buttonGroup[selectedItems[i]]) { // Make sure it's an array
                retArr[i] = buttonGroup[selectedItems[i]].value;
            } else { // It's not an array (there's just one check box and it's selected)
                retArr[i] = buttonGroup.value; // return that value
            }
        }
    }
    return retArr;
}

//Validator function to enforce max/min on textboxes
function EnforceMaxMinNumber(Min, Max, fieldID, name) {
    var returnValue = true;
    try {
        var fieldVal = document.getElementById(fieldID).value;
        returnValue = !isNaN(fieldVal) && Min <= parseFloat(fieldVal) && Max >= parseFloat(fieldVal);
        if (!returnValue)
            alert(name + " requires a number between " + Min + " and " + Max + ".");
    } catch (err) { alert('Error in EnforceMaxMinNumber: ' + err.message) };
    return returnValue;
}

//Check to make sure value in date input is a date
function TestValidDate(strDate) {
    var ReturnValue = true;
    try {
        var expDate = /^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4}$/;
        if (strDate != '') {
            if (strDate.search(expDate) == -1) {
                ReturnValue = false;
            } else {
                dtDate = new Date(strDate);
                datepart = strDate.split('/');
                if (!(datepart.length == 3 && parseInt(datepart[0], 10) == (dtDate.getMonth() + 1)
                    && parseInt(datepart[1], 10) == dtDate.getDate() && parseInt(datepart[2], 10) == dtDate.getFullYear())) {
                    ReturnValue = false;
                }
            }
        }
    } catch (err) { alert('Error in TestValidDate: ' + err.message) };
    return ReturnValue;
}

//Checks the file extension against the regex of allowed file types.
function ValidateFileUpload(FieldID, Question, AllowedFileTypes, ValidRegex) {
    try {
        if (ValidRegex.test(document.getElementById(FieldID).value)) {
            return true;
        } else {
            alert(Question + " requires a file of one of the following types: " + AllowedFileTypes);
            return false;
        }
    } catch (err) { alert('Error in ValidateFileUpload: ' + err.message) };
    return true
}

//Swaps out the current image for the one attached to the answer selected
function SwapQuestionImage(ImageID, AnswerText, ImageArray) {
    //If the image has valid answer text, reset the SRC attribute
    if (ImageArray[AnswerText].src != '')
        document.getElementById(ImageID).src = ImageArray[AnswerText].src;
}

//narrows down the questions to fit in survey popup
function ShrinkQuestions(tblArray) {
    var tblCount = 0;
    for (tblCount = 0; tblCount < tblArray.length; tblCount++) {
        tblArray[tblCount].style.width = "471px";
        tblArray[tblCount].style.margin = "0 auto"
    }
}

//If required questions were omitted on validation, this scrolls the survey to show them
function ScrollToPanel(PanelID) {
    var Panel = document.getElementById(PanelID)
    var Offset = Panel.offsetTop
    var PanelHeight = Panel.clientHeight
    Panel.parentNode.parentNode.scrollTop = Offset + PanelHeight;
}

//Gets the active button in the popup panel
function GetActiveButtonID(btnID, panel) {
    try {
        if (btnID != "") {
            var parts = btnID.split("ibtn");
            if (parts.length > 1) {
                var newID = parts[0] + "ibtnSurvey" + parts[1];
                if (document.getElementById(newID))
                    SetImageButtons(panel, newID)
            }
        }
    } catch (e) { }
}

//sets the button visibility in the popup panel
function SetImageButtons(container, IDToShow) {
    var inputs = container.getElementsByTagName("input");
    var i = 0;
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'image' && inputs[i].id != IDToShow) {
            inputs[i].style.display = 'none'
        } else {
            inputs[i].style.display = ''
        }
    }
}

//Turns survey into pop-up layer
function ShowSurveyPopup(SurveyPanelID, btnID) {
    try {
        if (SurveyPanelID != '') {
            pnlSurveyID = SurveyPanelID
            var SURVEY_WIDTH = 500
            var QuestionPanel = null;
            var HeaderPanel = null;
            var CloseThis = null;
            var HeaderPanelHeight = 0
            var HeaderNodes = null
            var NodeCount = 0
            var SurveyPanel = document.getElementById(SurveyPanelID);

            //If the containing element isn't a div, don't pop.
            if (SurveyPanel.tagName.toLowerCase() != 'div') {return false;}

            GetActiveButtonID(btnID, SurveyPanel)
            
            if (SurveyPanel.childNodes[1].className == 'PanelHeaderPermanent') {
                QuestionPanel = SurveyPanel.childNodes[3];
                HeaderPanel = SurveyPanel.childNodes[1];
            } else {
                QuestionPanel = SurveyPanel.childNodes[1];
                HeaderPanel = SurveyPanel.childNodes[0];
            }              

            //show the survey panel for a pop-up survey.
            SurveyPanel.style.display = "";
            SurveyPanel.style.zIndex = "1000";

            //Generic styleish stuff
            SurveyPanel.className = "DefaultPopup"
            QuestionPanel.style.borderBottom = "2px silver inset";

            //RESET OVERFLOW & HEIGHT
            QuestionPanel.style.height = 'auto';
            SurveyPanel.style.height = 'auto';
            QuestionPanel.style.overflow = '';

            //Set the position - DO NOT MOVE THIS UNLESS YOU WANT VERY TINY SURVEYS
            SurveyPanel.style.position = "absolute";
            SurveyPanel.style.width = SURVEY_WIDTH + "px";
            //hasLayout Hack for IE--the clientHeight will be WRONG without this
            QuestionPanel.style.width = "498px";
            SurveyPanel.style.top = "0px";
            SurveyPanel.style.left = "0px";

            //this makes room to place the vertical scrollbar.
            //if (SurveyPanel.childNodes[1].className != 'PanelHeaderPermanent')
            ShrinkQuestions(QuestionPanel.getElementsByTagName("div"))

            //Create the Close link
            if (document.getElementById('CloseLink') == null) {
                //create the close element       
                var imgClose = ""
                CloseThis = document.createElement('a');
                if (survCloseButtonPath == '') {
                    CloseThis.innerHTML = 'X';
                } else {
                    imgClose = document.createElement('img');
                    imgClose.src = survCloseButtonPath;
                    CloseThis.appendChild(imgClose);
                }
                CloseThis.style.paddingRight = '2px';
                CloseThis.id = 'CloseLink'
                CloseThis.style.position = 'absolute'
                CloseThis.style.right = '0px'
                CloseThis.style.top = '0px'
                CloseThis.onclick = function() { this.parentNode.parentNode.style.display = 'none' };
                CloseThis.className = 'link';
                HeaderPanel.appendChild(CloseThis);
                if (imgClose != "" && imgClose.clientHeight > 0 && imgClose.clientHeight > HeaderPanel.clientHeight) {
                    HeaderPanel.style.height = (imgClose.clientHeight + 2) + "px"
                } else if (HeaderPanel.clientHeight < 2)
                    HeaderPanel.style.height = '1.5 em';
                if (HeaderPanel.style.display != '')
                    HeaderPanel.style.display = '';
            }

            //Get the height of the survey panel            
            var QuestionHeight = QuestionPanel.clientHeight;
            var QuestionContentHeight = QuestionPanel.scrollHeight
            var SurveyHeight = SurveyPanel.clientHeight;
            var SurveyChrome = parseInt(SurveyHeight, 10) - parseInt(QuestionHeight, 10);
            var ScreenHeight = 0
            var ScreenWidth = 0
            var ScrollTop = 0

            //Get window height/width
            if (window.innerHeight)
                ScreenHeight = window.innerHeight;
            else
                ScreenHeight = document.body.parentNode.clientHeight;
            if (window.innerWidth)
                ScreenWidth = window.innerWidth;
            else
                ScreenWidth = document.body.parentNode.clientWidth;
            if (window.pageYOffset)
                ScrollTop = window.pageYOffset;
            else if (typeof (document.body.parentElement) != 'undefined')
                ScrollTop = document.body.parentElement.scrollTop;
            else
                ScrollTop = document.body.scrollTop;



            //If the panel is too long, compress the survey container
            if (SurveyHeight > ScreenHeight || (QuestionContentHeight + SurveyChrome) > ScreenHeight) {
                //set the survey panel to the height of the screen with a little padding
                SurveyPanel.style.height = ScreenHeight + "px"
                //Height of the questions should be screenheight - chrome - padding
                QuestionPanel.style.height = (ScreenHeight - SurveyChrome - 5) + "px"
                //this is set to allow for the position later
                SurveyHeight = ScreenHeight;
            } else if (QuestionContentHeight != QuestionHeight) {
                //Height of the questions should be screenheight - chrome - padding
                SurveyPanel.style.height = (QuestionContentHeight + SurveyChrome) + "px"
                QuestionPanel.style.height = (QuestionContentHeight) + "px"
                SurveyHeight = (QuestionContentHeight + SurveyChrome)
            } else {
                //Lock the height of the question panel to its current configuration
                QuestionPanel.style.height = QuestionHeight + "px"
            }

            //Now center the survey
            SurveyPanel.style.top = (((ScreenHeight - SurveyHeight) / 2) + ScrollTop) + "px";
            SurveyPanel.style.left = ((ScreenWidth - SURVEY_WIDTH) / 2) + "px";
            QuestionPanel.style.overflow = "auto"
        }
    } catch (ex) { alert("Error in ShowSurveyPopup: " + ex.message); }
    return false;
}


//handles trimming a string for use in validation
function sbp_trim(strToTrim) {
    return strToTrim.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 
}
