/// <reference path="LaunchNetClientBase.js"/>
/// <reference path="BrowserServices.js"/>
/// <reference path="ErrorServices.js"/>
/// <reference path="ClientProxyServices.js"/>
/// <reference path="LaunchNetClientContext.js"/>

var __surveySubmitClientId;
var __surveyClearClientId;
var __surveyErrorClientId;
var __surveyErrorText;
var __surveyPk;
var __surveyAnswClientTypesLookup;
var __surveyQuestPks;
var __surveyQuestClientIds;
var __surveyAnswPks;
var __surveyAnswClientIds;
var __surveyAnswClientTypes;
var __surveyAnswSequences;
var __surveyAnswIsNoAnswer;

function SurveyServices()
{
  this.OnPageClick = OnPageClick;
  this.OnValidationRequiredCheck = OnValidationRequiredCheck;

/* *********************************************************************************** 
-  Global variables
************************************************************************************ */                   

/* ***********************************************************************************
-  Page Click Event
************************************************************************************ */

  function OnPageClick(launchNetElementClicked, pageValid)
  {
    //If there is a survey and if the event implies the submission of a survey and validation has passed
    if(IsSurveySubmit(launchNetElementClicked) && pageValid)
    {
      SaveSurvey(launchNetElementClicked);
    }
  }

/* ***********************************************************************************
-  Page Validation
************************************************************************************ */

  function OnValidationRequiredCheck(launchNetElementClicked)
  {
    return IsSurveySubmit(launchNetElementClicked);
  }

  function IsSurveySubmit(launchNetElementClicked)
  {
    //old style survey behavior matches client id against db entry
    //new style matches command
    var isSurveySubmit = (launchNetElementClicked.Element.id == __surveySubmitClientId)
      || (launchNetElementClicked.HasCommand && launchNetElementClicked.Command == "SurveySubmit");
      
    return isSurveySubmit;
  }


  function SaveSurvey(launchNetElementClicked)
  {
    var SurveyObj;

    //create a survey manager
    SurveyObj = new SurveyObjectManager();

    //obtain observation pk related to this event
    //TODO this should be decoupled somehow..
    var observationPk = new ObservationServices().GetObservationPk(launchNetElementClicked);
    
    //save the survey (with the given observation code, normally 116)
    SurveyObj.SaveSurvey(observationPk);
  }
}



/************************************************************************************* 
Functions and objects that facilitate Surveys
**************************************************************************************/

/************************************************************************************* 
-  JScriptDYNSurveyObjects  This file contains JavaScript objects that 
-       facilitate dynamic survey implementation.
**************************************************************************************/
/* *********************************************************************************** 
-  Class: SurveyObjectManager   
-  Purpose: Records survey information.  This class represents a question 
-           and answer collection for a survey. It encapsulates question/answer
-           functionality.  
-  Date:  12/15/2006
-  Mods:  03/12/2008 FWH - streamlined to improve performance
-         04/01/2008 FWH - removed edit rule logic (replaced by new javascript validation)
************************************************************************************ */
function SurveyObjectManager()
{
// Constructor
  this.Init = Init();
      
// Public Function Declarations ////////////////////////
   this.SaveSurvey = SaveSurvey;

// Private Variable Declarations ////////////////////////
  var _ObservationID         //Observation number associated with this survey. 
  //Collections
  var _SurveyQuestObjArray;  //Question Object array of Javascript obects.
  //other arrays used by this js are built via injection through SurveyServices
      
////////////////////////////////////////////////////////
// Public Functions ////////////////////////////////////
/* *********************************************************************************** 
-  Function: Init  
-  Purpose: Constructor sets up any metadata for this question.  
-             
-  Parameters: thisEvnt - The event that initiated this class usually the submit button
-                         click.  We also could be processing a clear button.   
-  Date:  01/08/2007
-  Mods:  04/02/2008 FWH - Pretty much gutted this
-     
************************************************************************************ */
  function Init()
  {
    //build survey js objects (question/answers)
    SurveyQuestObjectFactory();
  }//End Init
  
/* *********************************************************************************** 
-  Function: SaveSurvey   
-  Purpose: Determines survey observation PK, derives answers for all questions, and saves survey. 
-  Parameters: None. 
-  Date:  04/02/2008
-  Mods:  
-     
************************************************************************************ */
  function SaveSurvey(observationPk)
  { 
    //Get Observation PK 
    _ObservationID = observationPk;
  
    var DynQuestObj;
    
    //Iterate thru all question objects and call the DeriveAnswer method on each one.
    for(var i = 0; i < _SurveyQuestObjArray.length; i++)
    {
      DynQuestObj = _SurveyQuestObjArray[i];
      DynQuestObj.DeriveAnswer();
    }

    SaveSurveyObservation();
  }
  
/* *********************************************************************************** 
-  Function: SaveSurveyObservation   
-  Purpose: Iterates thru question collection and collects question/answer data, then
-           calls the server-side method to insert data to database. 
-  Parameters: None. 
-  Date:  04/02/2008
-  Mods:  
-     
************************************************************************************ */
  function SaveSurveyObservation()
  {
    var DynQuestObj;
    var DynAnsObj;
    var AnsObjArray;
    var QuestPK;
    var AnsPK;
    var AnsData;

    var surveyArray = new Array();
    var pos = 0;
    
    //Iterate thru question collection and call server side to insert data
    for(var i = 0; i < _SurveyQuestObjArray.length; i++)
    {
      DynQuestObj = _SurveyQuestObjArray[i];
      QuestPK = DynQuestObj.GetQuestionPK();
      AnsObjArray = DynQuestObj.GetAnsObjColl();

      var submitData;
      submitData = new Object();
      
      submitData.QuestPk = QuestPK;
      
      if(DynQuestObj.IsQuestionAnswered())
      {
        //Iterate thru associated answer collection and get data if answer data is 
        //present.  If the question is NOT answered, insert a 'No Answer' row.
        for(var ii = 0; ii < AnsObjArray.length; ii++)
        {
          DynAnsObj = AnsObjArray[ii];
          if(DynAnsObj.GetIsData())
          {
            submitData.AnswData = DynAnsObj.GetAnswerData();
            submitData.AnswPk = DynAnsObj.GetAnsPK();
          }
        }
      }
      else
      {
        //This is a no answer so find the no answer answer
        // and get the proper QVC etc... 
        for(var iii = 0; iii < AnsObjArray.length; iii++)
        {
          DynAnsObj = AnsObjArray[iii];
          if(DynAnsObj.GetNoAns())
          {
            submitData.AnswData = "";
            submitData.AnswPk = DynAnsObj.GetAnsPK();
          }
        }
      }
      
      surveyArray[pos] = submitData;
      pos++;
    }
    
    __context.GetSurveyServicesClientProxy().ClientCompleteSurvey(__sessionPk, _ObservationID, surveyArray);
  }

/* *********************************************************************************** 
-  Function: SurveyQuestObjectFactory   
-  Purpose: Returns a SurveyQuestion object array with all metadata. 
-  Parameters: SurObjType - The type of object that we want created. 
-  Date:  04/02/2008
-  Mods:  
-     
************************************************************************************ */
  function SurveyQuestObjectFactory(SurObjType)
  {
    var pos = 0;
    var SurvObj;                        //Individual Javascript question object
    var ResultArray = new Array();      //Javascript object Question objects.

    for (var i = 0; i < __surveyQuestPks.length; i++)
    {
      var questionElement = null;
      
      if (__surveyQuestClientIds[i].length > 0)
      {
        questionElement = document.getElementById(__surveyQuestClientIds[i]);
      }
      
      if (questionElement != null)
      {
        //indicates the question is present on this page
        //create the question javascript object, and the related answer data

        SurvObj = new SurveyQuestion(__surveyQuestPks[i], __surveyQuestClientIds[i], i);
        ResultArray[pos] = SurvObj;
        pos++;
      }
    }

    //place all questions in array
    _SurveyQuestObjArray = ResultArray;
  }
  

}//End  SurveyObjectManager
//*End SurveyObjectManager Class ************************************************************/  


/* *********************************************************************************** 
-  Class: SurveyQuestion   
-  Purpose: This class represents a question 
-           and associated answer collection for a survey. It encapsulates question/answer functionality.  
-  Date:  04/02/2008
-  Mods:  
-     
************************************************************************************ */
function SurveyQuestion(QPk,QClientID,QIdx)
{
// Constructor
  this.Init = Init(QPk,QClientID,QIdx);
  this.DeriveAnswer = DeriveAnswer;
  
// Public Property Declarations ////////////////////////
// Property Getters
// Property GetQuestionID -         
  this.GetQuestionID = GetQuestionID; 
  function GetQuestionID()
  {
    return _QuestClientId;
  }
// Property GetQuestionPK -          
  this.GetQuestionPK = GetQuestionPK; 
  function GetQuestionPK()
  {
    return _thisQuestionPk;
  }
// Property GetAnsObjColl -             
  this.GetAnsObjColl = GetAnsObjColl; 
  function GetAnsObjColl()
  {
    return _SurveyAnsObjArray;
  } 
// Property GetQuestionQVA -         
  this.GetQuestionQVA = GetQuestionQVA; 
  function GetQuestionQVA()
  {
    return _QuestQVA;
  } 
  // Property IsQuestionAnswered -         
  this.IsQuestionAnswered = IsQuestionAnswered; 
  function IsQuestionAnswered()
  {
    return _DataExists;
  }                               

// Private Variable Declarations ////////////////////////
  var _thisQuestionPk;       //Question Primary Key.
  var _QuestClientId;        //HTML ID of the question on the client.  
  var _QuestQVA;
  var _SurveyAnsObjArray;
  var _DataExists;
      
////////////////////////////////////////////////////////
// Public Functions ////////////////////////////////////
/* *********************************************************************************** 
-  Function: Init  
-  Purpose: Constructor sets up the question object.  It populates variables
-           and the associated answer collection    
-  Parameters: QPk - Primary Key of the question object. 
-              QClientID - HTML ID of the question on the client.  
-              QIdx - The index of the question in the SurvQuest arrays
-  Date:  04/02/2008
-  Mods:  
-     
************************************************************************************ */
  function Init(QPk,QClientID,QIdx)
  {             
    //Set up private vars
    _thisQuestionPk = QPk;
    _QuestClientId = QClientID;

    //Get Javascript object array of answers
    SurveyAnsObjectFactory(QIdx);

  }//End Init

/* *********************************************************************************** 
-  Function: DeriveAnswer
-  Purpose: For this question iterate thru the answer collection and determine the selected response
-  Parameters: None. 
-  Date:  04/02/2008
-  Mods:  
-     
************************************************************************************ */
  function DeriveAnswer()
  { 
    var checkObj;               //Current question HTML object
    var AnsDynObj;              //Single SurveyAnswer Javascript object.

    //Iterate thru answer collection and call the DeriveAnswer method
    //on each individual object. 
    for(var i = 0; i < _SurveyAnsObjArray.length; i++)
    {
      AnsDynObj = _SurveyAnsObjArray[i];
      AnsDynObj.DeriveAnswer();

      switch(AnsDynObj.GetAnsType())
      {
      case "radio":
        if(AnsDynObj.GetIsData())
        {
          _DataExists = true;
        }    
        break;
        
      case "checkbox":
        if(AnsDynObj.GetIsData())
        {
          _DataExists = true;
        }    
        break;
        
      }
    }
    
  } //End ApplyEdits
  
/////////////////////// Private Methods ///////////////////////////////////
/* *********************************************************************************** 
-  Function: SurveyAnsObjectFactory  
-  Purpose: Returns an associated SurveyAnswer object array with all metadata. 
-  Parameters: QIdx - The index of the question to create answer collection for
-  Date:  04/02/2008
-  Mods:  
-     
************************************************************************************ */
  function SurveyAnsObjectFactory(QIdx)
  {             
    var ResultArray = new Array();  //Array of Javascript SurveyAnswer
    var AnsSurvObj;                 //Individual Ans Javascript object.
    var pos = 0;
    
    for (var i = 0; i < __surveyAnswPks[QIdx].length; i++)
    {
      AnsSurvObj = new SurveyAnswer(
        __surveyAnswPks[QIdx][i]
        ,__surveyAnswClientIds[QIdx][i]
        ,__surveyAnswClientTypes[QIdx][i]
        ,__surveyAnswSequences[QIdx][i]
        ,__surveyAnswIsNoAnswer[QIdx][i]
      );
      
      ResultArray[pos] = AnsSurvObj;
      pos++;
    }

    //Save the Javasctipt SurveyAnswer array.
    _SurveyAnsObjArray = ResultArray;
  }
}//End SurveyQuestion
//*End SurveyQuestion Class ************************************************************/  

/* *********************************************************************************** 
-  Class: SurveyAnswer   
-  Purpose: Encapsulates Survey answer functionality.  This class represents an answer
-           to a question for a survey. 
-  Date:  04/02/2008
-  Mods:  
-     
************************************************************************************ */
function SurveyAnswer(AnsPk,AnsClientID,AnsType,AnsSeq,IsNoAnswer)
{
// Constructor
  this.Init = Init(AnsPk,AnsClientID,AnsType,AnsSeq,IsNoAnswer);
  this.DeriveAnswer = DeriveAnswer;
  
// Public Property Declarations ////////////////////////
// Property Getters
  this.GetAnswerData = GetAnswerData; 
  function GetAnswerData()
  {
    return _AnswerData;
  }
  this.GetIsData = GetIsData; 
  function GetIsData()
  {
    return _IsData;
  }             
  this.GetAnsPK = GetAnsPK; 
  function GetAnsPK()
  {
    return _AnsPk;
  }  
  this.GetAnsType = GetAnsType; 
  function GetAnsType()
  {
    return __surveyAnswClientTypesLookup[_AnsType];
  }                              
  this.GetAnsSeq = GetAnsSeq; 
  function GetAnsSeq()
  {
    return _AnsSeq;
  } 
  this.GetNoAns = GetNoAns; 
  function GetNoAns()
  {
    return _IsNoAns;
  } 
                        
// Private Variable Declarations ////////////////////////

  var _AnsPk;
  var _AnsClientID;
  var _AnsType;
  var _AnswerData;
  var _IsData;
  var _AnsSeq;
  var _IsNoAns;
  var _thisObj;

////////////////////////////////////////////////////////
// Public Functions ////////////////////////////////////
/* *********************************************************************************** 
-  Function: Init  
-  Purpose: Constructor sets up the answer object.  It populates variables
-           and initializes the associated answer.        
-  Parameters: AnsClientID - ID of the Answer HTML tag. 
-              AnsType - The type of HTML object i.e. radiobutton, textbox etc.   
-              AnsPk - Primary Key of the Answer.  
-              AnsSeq - Numeric position of the answer object.
-  Date:  04/02/2008
-  Mods:  
-     
************************************************************************************ */
  function Init(AnsPk,AnsClientID,AnsType,AnsSeq,IsNoAnswer)
  {             
    //Set up private vars
    _AnsPk = AnsPk; 
    _AnsClientID = AnsClientID;
    _AnsType = AnsType;
    _AnsSeq = AnsSeq;
    _IsNoAns = IsNoAnswer
    _IsData = false; 
    _AnswerData = null;
    _thisObj = GetMe();

  }//End Init

/* *********************************************************************************** 
-  Function: DeriveAnswer
-  Purpose: Derives the answer for the HTML object. 
-  Parameters: None. 
-  Date:  04/02/2008
-  Mods:
-     
************************************************************************************ */
  function DeriveAnswer()
  { 
    var checkObj;               //HTML answer object.
    var objLength;
    var retval = false;
    var wkObj;
    var objValue;

    //Get the HTML answer object
    checkObj = _thisObj;

    //Do we have the object on this page???
    if(checkObj != null)
    {
      //determine the answer          

      switch(GetAnsType())
      {
      case "radio":
        if(checkObj.checked)
        {
          _IsData = true;
          _AnswerData = "true";
        }
        break;
      
      case "text":
        objValue = checkObj.value;
        if(objValue.length > 0)
        {
          _IsData = true;
          _AnswerData = objValue;
        }
        break;
        
      case "checkbox":
        if(checkObj.checked)
        {
          _IsData = true;
          _AnswerData = "true";
        }     
        break;   
      }
      
    }

  } //End ApplyEdits
  
  
/* *********************************************************************************** 
-  Function: GetMe 
-  Purpose: Returns the correct survey answer object depending upon the object type
-           or browser type. 
-  Parameters: None. 
-  Date:  10/15/2007
-  Mods:
-     
************************************************************************************ */        
  function GetMe()
  {
    var retobj = null;

    if (_AnsClientID.length > 0)
    {
      retobj = document.getElementById(_AnsClientID);
    }
    
    //See if we have an ID.   
    if(GetObjID(retobj)== null)
    {
      //No ID see if this is a radio/checkbox array
      //Look for the name. 
      retobj = document.getElementsByName(_AnsClientID);
    }
    
    //If we are in an array get the correct element. 
    if(retobj.length > 1)
    {
      retobj = retobj[_AnsSeq];
    }

    return retobj;
  }
  
/* *********************************************************************************** 
-  Function: GetObjID 
-  Purpose: Determines if an ID exists for the object.  An ID may not exist if:
-           1) This is a NO ANSWER - it will have no manifestation in the screen.
-           2) This is a radio/checkbox array, which has a NAME not an ID.     
-  Parameters: None. 
-  Date:  10/15/2007
-  Mods:
-     
************************************************************************************ */               
  function GetObjID(obj)
  {
    var ObjId 

    if(obj == null)
    {
      return null;
    }

    ObjId = obj.id;
    switch(ObjId)
    {
    case "":
      return null;
      break;
    case null:
      return null;
      break;
    default:
      return ObjId;
      break;
    }
  }

}//End  SurveyAnswer
//*End SurveyAnswer Class ************************************************************/  


