﻿// JScript File

//global values
var http_request = false;
var ContainerPrefix = "";
var arrButtons;
var QuestionLockState = null;
var PleaseWaitID = "";
var CountQuestions = null;
var pnlSurveyID = "";
var surveyFnUpdatePreview = function () {};
var survCloseButtonPath = ""

//Constants
var CSS_CLASS_POPUP = "DefaultPopup";
var CSS_CLASS_ROW = "RowStyle";
var CSS_CLASS_ALTERNATE = "AlternatingRowStyle"

function getSelectedRadio(buttonGroup) {
	    
	   // returns the array number of the selected radio button or -1 if no button is selected
	   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;
	} // Ends the "getSelectedRadio" function
	
	function getSelectedCheckbox(buttonGroup) {
	   // 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)
	   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;
	} // Ends the "getSelectedCheckbox" function
	
	function getSelectedCheckboxValue(buttonGroup) {
	   // 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)
	   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;
	} // Ends the "getSelectedCheckBoxValue" function

function SubmitSurveyChanges(buttons, prefix, FieldID, SurveyResultDetailID, DataType, SurveyResultsID, ServiceURL, PleaseWait) 
{    
    //alert(prefix + "\n" + FieldID + "\n" + SurveyResultDetailID + "\n" + DataType + "\n" + SurveyResultsID + "\n" + ServiceURL);
    ContainerPrefix = prefix;
    arrButtons = buttons; 
    PleaseWaitID = PleaseWait; 
        
    //is this a radio button or not?
    if(DataType==4)
    {
        //radio button
        SurveyFieldValue = getSelectedRadio(document.getElementById(FieldID));
    }
    else if(DataType==2)
    {
        SurveyFieldValue = getSelectedCheckboxValue(document.getElementById(FieldID));
        //alert(SurveyFieldValue);
    }
    else
    {
        //alert('Field_' + SurveyResultDetailID + '=' + FieldName.value);
        SurveyFieldValue = document.getElementById(FieldID).value;
    }

    //Replace spaces so that they can be sent in the URL
    SurveyFieldValue = escape(SurveyFieldValue);
    
    //submit survey field value
    DisableButtons(true)
    url = ServiceURL //+ "/SetSurveyResultQuestionAnswerValue";
    parameters = "function=SetSurveyResultQuestionAnswerValue&IsCompass=True&"
    parameters = parameters + "SurveyResultsID="+ SurveyResultsID +"&SurveyResultDetailID="+ SurveyResultDetailID +"&AnswerText=" + SurveyFieldValue ;  
				
	makeSurveyPOSTRequest(url, parameters, 1);			
}

function InitialSetup(prefix, SurveyResultsID, ServiceURL)
{    
    //retrieve show/hide XML
    url = ServiceURL //+ "/GetSurveyQuestionVisibility";
    parameters = "function=GetSurveyQuestionVisibility&IsCompass=True&"
    parameters = "SurveyResultsID=" + SurveyResultsID;
    
    ContainerPrefix = prefix;
    
    //window.prompt("URL To Use", url + "?" + parameters)
				
	makePOSTRequest(url, parameters, 1);
}

function makeSurveyPOSTRequest(url, parameters, IsSave) 
{
   try{
        http_request = false;
        if (window.XMLHttpRequest) 
        { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) 
            {
                http_request.overrideMimeType('text/xml');
            }
        } 
        else if (window.ActiveXObject) 
        { // IE
            try 
            {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } 
            catch (e) 
            {
                try 
                {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } 
                catch (e){}
            }
        }
        		  
        if (!http_request) 
        {
            alert('Cannot create XMLHTTP instance');
            return false;
        }
        
        if(IsSave != 0)      
        {
            http_request.onreadystatechange = ProcessSurveyContents;  
            
            //lock the fields -- this is a save, will be unlocked later
            LockQuestions(true);
            CallPleaseWait()     
        }       
           
        //prompt("URL:", url + "?" + parameters);
        	      
        //http_request.open('POST', url, true);
        http_request.open('POST', url + "?" + parameters, true);
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", parameters.length);
        http_request.setRequestHeader("Connection", "close");
        http_request.send(parameters);
    }
    catch (e)
    {
        //In the event of an error, release the loop and enable buttons
        DisableButtons(false);
        
        //release questions
        LockQuestions(false)
        
        //Hides the Please Wait function
        KillPleaseWait()
    }
}

function ProcessSurveyContents() 
{
    var MasterNodeName = "Question"		
    if (http_request.readyState == 4) 
    {
        if (http_request.status == 200) 
        {	
            if (window.XMLHttpRequest) 
            { // Mozilla, Safari,...				
                var xmldoc = http_request.responseXML;             
                var questions = xmldoc.getElementsByTagName('QuestionVisibility');               
                					
                //loop through the results and show or hide questions accordingly
                for(var i=0; i<questions.length; i++) 
                {
                    QuestionID = questions[i].attributes[0].value;                    
                    QuestionEnabled = questions[i].firstChild.nodeValue;   
                    						
                    //Show or hide questions based on the result
                    if(QuestionEnabled == "true") 
                    {                        
                        if(document.getElementById(ContainerPrefix + QuestionID))
                            document.getElementById(ContainerPrefix + QuestionID).style.display = "";
                    }
                    else
                    {
                        if(document.getElementById(ContainerPrefix + QuestionID))
                            document.getElementById(ContainerPrefix + QuestionID).style.display = "none";
                    }				
                }							
            } 
            else if (window.ActiveXObject) 
            { // IE	               
                result = http_request.responseText;
                var xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
                xmlDoc.async="false"
                xmlDoc.loadXML(result)
            				
                arrQuestions = xmlDoc.getElementsByTagName("QuestionVisibility");
            					
            					
                //loop through the xml results and show or hide surveys accordingly
                for(var i=0; i<arrQuestions.length; i++) 
                {
                    QuestionID = arrQuestions[i].attributes(0).value;
                    QuestionEnabled = arrQuestions[i].firstChild.nodeValue;                  
                						
                    //Show or hide questions based on the result
                    if(QuestionEnabled == "true") 
                    {
                        if(document.getElementById(ContainerPrefix + QuestionID))
                            document.getElementById(ContainerPrefix + QuestionID).style.display = "";
                    }
                    else
                    {
                        if(document.getElementById(ContainerPrefix + QuestionID))
                            document.getElementById(ContainerPrefix + QuestionID).style.display = "none";                        
                    }
                }	
            }
        }
        else 
        {
            alert('There was a problem with the request. Status is ' + http_request.status );
        }
        
        //release form buttons
        DisableButtons(false)
        
        //release questions
        LockQuestions(false)
        
        //reset the visible area
        ShowSurveyPopup(pnlSurveyID)
        
        //count the questions & update status
        if(typeof(CountQuestions) == 'function')
            try{
               CountQuestions.call(this)
            }catch(e){alert("Call Failed: " + e.message);}
        
        //update any previews that have been configured
        surveyFnUpdatePreview();
        
        //Hides the Please Wait message
        KillPleaseWait()
    }  
    
}


function LockSurveys(LockState, SurveyForm)
{
    try
    {
        var arrDivList = SurveyForm.getElementsByTagName("div");
        var arrInputs =  new Array;
        var i, j;
        
        //reset if we're locking
        if(LockState)
            QuestionLockState = new Object();
        
        for(i=0; i < arrDivList.length; i++)
        {
            if(arrDivList[i].className == "QuestionDiv")
            {
                arrInputs = arrDivList[i].getElementsByTagName("input");
                for(j=0; j < arrInputs.length; j++)
                {
                    //arrInputs[j].disabled = LockState;              
                    LockField(arrInputs[j], LockState);             
                }
                arrInputs = arrDivList[i].getElementsByTagName("select");
                for(j=0; j < arrInputs.length; j++)
                {
                    //arrInputs[j].disabled = LockState;              
                    LockField(arrInputs[j], LockState);
                }            
            }
        }
    }
    catch(e)
    {
        //alert('LockSurveys: ' + e.message);
    }
}

function LockField(Field, State)
{
    if(State)
    {
        //lock the field and log its status
        QuestionLockState[Field.id] = Field.disabled;
        Field.disabled = State;
    }
    else
    {
        //restore according to initial status
        if(!QuestionLockState[Field.id])
        {
            //this field was originally enabled
            Field.disabled = State;
        }
    }
}

function DisableButtons(Disable)
{
    var i = 0;
    for(i=0; i < arrButtons.length; i++)
    {
        try
        {
            if(document.getElementById(arrButtons[i]))
                document.getElementById(arrButtons[i]).disabled = Disable;
        }
        catch(e){}
    }
}

function LockQuestions(LockState)
{
   //-- lop off trailing underscore to get container ID
    try{
        //get the survey container
        SurveyForm = document.getElementById(ContainerPrefix + 'pnlDefaultBody');
        
        //add code to show the Loading message
       
       //lock/release the questions
       LockSurveys(LockState, SurveyForm);
       
       //add code to hide the Loading message
    }catch(e){
       // alert('FAIL: ' + e.message)
    }
}

//handle Please Wait functions 
function CallPleaseWait()
{
     //Hide please wait
        try
        {
            if(typeof document.getElementById(PleaseWaitID) != "undefined")
            {
                ShowPleaseWait(PleaseWaitID);
            }
        }catch(e){
        }
}

function KillPleaseWait()
{
     //Hide please wait
        try
        {
            if(typeof document.getElementById(PleaseWaitID) != "undefined")
            {
                HidePleaseWait(PleaseWaitID);
            }
        }catch(e){
        }
}


//These functions handle the Images for questions that use ordinal classes with images

//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;
}

function ShrinkQuestions(tblArray)
{
    var tblCount = 0;
    for(tblCount=0; tblCount < tblArray.length; tblCount++)
        tblArray[tblCount].style.width = "480px";
}

function ScrollToPanel(PanelID)
{
    var Panel = document.getElementById(PanelID)
    var Offset = Panel.offsetTop
    var PanelHeight = Panel.clientHeight
    Panel.parentNode.scrollTop = Offset + PanelHeight;
}

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){}
}

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 = ''}            
    }
}

function ShowSurveyPopup(SurveyPanelID, btnID)
{
    try{
        if(SurveyPanelID != ''){
            pnlSurveyID = SurveyPanelID
            var SURVEY_WIDTH = 500
            var SurveyPanel = document.getElementById(SurveyPanelID);
            GetActiveButtonID(btnID, SurveyPanel)
            var QuestionPanel = null;
            var HeaderPanel = null;   
            var CloseThis = null;
            var HeaderPanelHeight = 0
            var HeaderNodes = null
            var NodeCount = 0
            
            if(SurveyPanel.childNodes[1].className == 'PanelHeaderPermanent'){ 
                QuestionPanel = SurveyPanel.childNodes[3].childNodes[1];
                HeaderPanel = SurveyPanel.childNodes[1];
            }else{
                QuestionPanel = SurveyPanel.childNodes[1].childNodes[0];
                HeaderPanel = SurveyPanel.childNodes[0];
            }  
            
            //show the survey panel for a pop-up survey.
            SurveyPanel.style.display = "";
            
            //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(e){
        alert(e.message);
    }
    return false;
}

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(e){alert(e.message)};
    return returnValue;
}