23. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 6/22/2017 10:29:11 AM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

23.1 Files compared

# Location File Last Modified
1 RAMS_CIF.zip\RAMS_CIF\RAMS_CIF\scripts\RAMS_SQA_Deployment_Files_V3_20150128\rams-ui\Production Environment RAMS-UI\js dynamicGeneration.js Thu Jun 22 12:35:46 2017 UTC
2 RAMS_CIF.zip\RAMS_CIF\RAMS_CIF\scripts\RAMS_SQA_Deployment_Files_V3_20150128\rams-ui\Production Environment RAMS-UI\js dynamicGeneration.js Thu Jun 22 14:33:49 2017 UTC

23.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 5 3458
Changed 4 8
Inserted 0 0
Removed 0 0

23.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

23.4 Active regular expressions

No regular expressions were active.

23.5 Comparison detail

  1   /********* ********** ********** ********** ********** **
  2   E1.1.0 RAM  Increment  1 Patch C ode
  3   January 20 15
  4   Department  of Vetera n's Affair s/Booz All en Hamilto n
  5   dynamicGen eration.js
  6   ********** ********** ********** ********** ********** */
  7  
  8   //template  to hold o verall stu dy with al l display  info
  9   var study;
  10  
  11   //template  to keep t rack of wh ich questi ons are an swered in  a section
  12   var change dQuestions ;
  13  
  14   //template  to keep t rack of al l the curr ent users
  15   var users;
  16  
  17   //template  to hold a ll respons es from a  user
  18   var rollup ;
  19  
  20   //template  to keep t rack of if  the study  is in dra ft or in r eview
  21   var recent Stage;
  22  
  23   //template  for the s tudy title
  24   var studyT itle;
  25  
  26   //study ti tle's id
  27   var studyT itleID = " 0";
  28  
  29   //template  for the s tudy ID
  30   var assign edID = "1" ;
  31  
  32   //template  for map b etween par ent/child  questions
  33   var depend ency = new  Hashtable ();
  34  
  35   //holds th e PI and C O-PI as th ey're fill ed out
  36   var studyP I = new Ha shtable();
  37  
  38   //Set of a ll answer  IDs that a re in the  rollup
  39   var rollup Answers =  new HashSe t();
  40  
  41   //Linking  in the sql  database
  42   var restPa th = "http :// SERVER : PORT /RAMS-0.0. 1/";
  43   //Linking  in the sha repoint si te
  44   var siteUr l = "http: // SERVE R
/sites/IRB Applicatio ns/";
  45  
  46   //template  for the u ser.
  47   var curren tUser={
  48       "displ ayName": " initialUse r",
  49       "login Name": nul l,
  50       "perma nentLoginI dentifier" : null,
  51       "users ID": null
  52   };
  53  
  54   //Inital f unction ca lled by HT ML. Sets u p baseline  informati on needed.
  55   function p rocess(){
  56       //Grab s username  and study  ID
  57       getCoo kie();
  58  
  59       //Gett ing the mo st recent  stage to u se later
  60       if(ass ignedID !=  "1"){
  61           st udyRespons e = sendRE ST("GET",  "study/"+a ssignedID,  null, fal se);
  62           if (!("length " in study Response.s tudy.study StatusColl ection))
  63                studyRes ponse.stud y.studySta tusCollect ion = [stu dyResponse .study.stu dyStatusCo llection];
  64           re centStage  = studyRes ponse.stud y.studySta tusCollect ion.length ;
  65       }else{
  66           re centStage  = parseInt (assignedI D);
  67       }
  68  
  69       //most  recent fo rms
  70       recent Forms = se ndREST("GE T", "forms ", null, f alse);
  71  
  72       //gett ing all in itial ques tions
  73       study  = sendREST ("GET", "f orms/"+rec entForms.f ormVersion [0].formVe rsionsID,  null, fals e);
  74  
  75       //buil ding secti on A
  76       sectio nBuilder(0 );
  77   };
  78  
  79   //Getting  user's res ponses fro m the data base and u pdating th e local ve rsion of
  80   //the user 's respons es, called  rollupAns wers
  81   function g etRollup() {
  82  
  83       //all  user's res ponses tha t are in t he databas e
  84       if(ass ignedID!=" 1"){
  85           // When the a ssignedID  is set to  1, we know  that ther e is no da ta in the  database f or a study
  86           ro llup = sen dREST("GET ", "study/ "+assigned ID+"/respo nses/"+rec entStage+" /rollup",  null, fals e);
  87  
  88           // formatting  the recie ved JSON
  89           if (!("respon ses" in ro llup.quest ionRespons eUpdates)) {
  90                rollup.q uestionRes ponseUpdat es.respons es = [];
  91           }e lse if(!(" length" in  rollup.qu estionResp onseUpdate s.response s)){
  92                rollup.q uestionRes ponseUpdat es.respons es = [roll up.questio nResponseU pdates.res ponses];
  93           }
  94  
  95           // below we a re statica lly grabbi ng the stu dy title,  PI, and CO -PI based  on generat ed positio n
  96           st udyTitleID  = study.f orm.contai nedFormCol lection[0] .contained Form.formQ uestionCol lection[0] .question. questionsI D;
  97  
  98           fo r(var j=0;  j<rollup. questionRe sponseUpda tes.respon ses.length ; j++){
  99                if(rollu p.question ResponseUp dates.resp onses[j].a nswersID){
  100                    roll upAnswers. add(rollup .questionR esponseUpd ates.respo nses[j].an swersID);
  101                }
  102  
  103                //settin g study ti tle
  104                if(rollu p.question ResponseUp dates.resp onses[j].q uestionsID  == studyT itleID)
  105                    stud yTitle = r ollup.ques tionRespon seUpdates. responses[ j].respons e;
  106  
  107           }
  108       }else{
  109           // setting an  empty rol lup
  110           ro llup = {};
  111       }
  112   };
  113  
  114   //getting  the user a nd study i d that was  passed to  the appli cation
  115   function g etCookie() {
  116       var us erCookie,  studyCooki e, splitUR L;
  117  
  118       //find ing the us er informa tion in th e database  
  119       users  = sendREST ("GET", "u ser", null , false);
  120           
  121       splitU RL = windo w.location .href.spli t("?");
  122  
  123       //stud y id that  was passed
  124       assign edID = spl itURL[1];
  125  
  126       //user  that was  passed
  127       curren tUser.disp layName =  splitURL[2 ];
  128  
  129       //look ing the us er up in t he databas e
  130       for(va r i=0; i<u sers.user. length; i+ +){
  131           if (users.use r[i].displ ayName ==  currentUse r.displayN ame)
  132                currentU ser.loginN ame = user s.user[i]. loginName;
  133       }
  134   };
  135  
  136   //sets up  the struct ure of the  question/ sidebar se ction and 
  137   //attaches  to the pr oper area  in webpage .
  138   function s ectionBuil der(target Section){
  139       rollup Answers =  new HashSe t();
  140       
  141       //upda ting the u ser's resp onses ever y time a n ew
  142       //sect ion is bui lt
  143       getRol lup();
  144  
  145       //remo ving any t race of th e last sec tion that  was built
  146       $('div .row').rem ove();
  147       var se ction, row , column,  sideColumn ;
  148       
  149       //sett ing up the  initial s tructure o f page
  150       row =  document.c reateEleme nt("div");
  151       row.se tAttribute ("class",  "row");
  152       $('div #insert'). append(row );
  153  
  154       column  = documen t.createEl ement("div ");
  155       column .setAttrib ute("class ", "col-xs -9");
  156       $('div .row').app end(column );
  157  
  158       column Builder(ta rgetSectio n);
  159  
  160       sideCo lumn = doc ument.crea teElement( "div");
  161       sideCo lumn.setAt tribute("c lass", "co l-xs-3 too lbar");
  162       $('div .row').app end(sideCo lumn);
  163  
  164       sideCo lumnBuilde r(targetSe ction);
  165   };
  166  
  167   //sets up  the struct ure of the  question  area; incl udes heade r,
  168   //question s, and but ton dock ( progress b uttons)
  169   function c olumnBuild er(targetS ection){
  170       var pa geHeader,  formConten t, progres sContainer ;
  171  
  172       sectio n = study. form.conta inedFormCo llection[t argetSecti on];
  173  
  174       //page  header
  175       pageHe ader = doc ument.crea teElement( "div");
  176       pageHe ader.setAt tribute("c lass", "pa ge-header" );
  177       $('div .col-xs-9' ).append(p ageHeader) ;
  178  
  179       header Builder(ta rgetSectio n);
  180  
  181       //ques tions
  182       formCo ntent = do cument.cre ateElement ("div");
  183       formCo ntent.setA ttribute(" class", "f ormContent ");
  184       $('div .col-xs-9' ).append(f ormContent );
  185  
  186       if((ta rgetSectio n == 1) ||  (targetSe ction == 5 ) || (targ etSection  == 6) || ( targetSect ion == 7)  || (target Section ==  11))
  187           di sclaimerBu ilder(targ etSection) ;
  188  
  189       questi onBuilder( section);
  190       
  191       //prog ress butto ns
  192       progre ssContaine r = docume nt.createE lement("di v");
  193       progre ssContaine r.setAttri bute("clas s", "progr ess-contai ner");
  194       $('div .col-xs-9' ).append(p rogressCon tainer);
  195  
  196       progre ssBuilder( targetSect ion);
  197   };
  198  
  199   //Sets up  the struct ure of the  sidebar;  includes s ection but tons, prin t and uplo ad buttons ,
  200   //and revi ew and sub mit button s.
  201   function s ideColumnB uilder(tar getSection ){
  202       var ac tionBar, w sBar;
  203  
  204       //acti on bar
  205       action Bar = docu ment.creat eElement(" div");
  206       action Bar.setAtt ribute("cl ass", "act ionbar");
  207       $('div .col-xs-3' ).append(a ctionBar);
  208  
  209       action BarBuilder (targetSec tion);
  210  
  211       //well  sidebar
  212       wsBar  = document .createEle ment("div" );
  213       wsBar. setAttribu te("class" , "well si debar");
  214       $('div .col-xs-3' ).append(w sBar);
  215  
  216       wellSi debarBuild er(targetS ection);
  217   };
  218  
  219   //creating  the discl aimer that  is seen a t the top  of certain  page
  220   function d isclaimerB uilder(tar getSection ){
  221       var co nt, close,  hide, clo ser, parag raph;
  222       cont =  document. createElem ent("div") ;
  223       cont.s etAttribut e("class",  "well not ificationA rea alert- dismissibl e fade in" );
  224       cont.s etAttribut e("role",  "Alert");
  225  
  226       close  = document .createEle ment("butt on");
  227       close. setAttribu te("data-d ismiss", " alert");
  228       close. setAttribu te("class" , "close") ;
  229       close. setAttribu te("type",  "button") ;
  230  
  231       hide =  document. createElem ent("span" );
  232       hide.s etAttribut e("aria-hi dden", "tr ue");
  233       var te xt = docum ent.create TextNode(" x");
  234       hide.a ppendChild (text);
  235  
  236       closer  = documen t.createEl ement("spa n");
  237       closer .setAttrib ute("class ", "sr-onl y");
  238       var te xt = docum ent.create TextNode(" Close")
  239       closer .appendChi ld(text);
  240  
  241       close. appendChil d(hide);
  242       close. appendChil d(closer);
  243  
  244       paragr aph = docu ment.creat eElement(" p");
  245  
  246       if(tar getSection  == 1){
  247           va r text = d ocument.cr eateTextNo de("Discla imer: Answ ers to som e question s in this  section wi ll require  your answ er to addi tional que stions in  subsequent  sections  of the IRB  Applicati on.");
  248       }else  if(targetS ection ==  5){
  249           va r text = d ocument.cr eateTextNo de("Discla imer: Base d on your  answers in  Section B , you are  required t o answer t hese addit ional ques tions.");
  250       }else  if(targetS ection ==  6){
  251           va r text = d ocument.cr eateTextNo de("Discla imer: Base d on your  answers in  Section B , you are  required t o answer t hese addit ional ques tions.");
  252       }else  if(targetS ection ==  7){
  253           va r text = d ocument.cr eateTextNo de("Discla imer: Base d on your  answers in  Section B , you are  required t o answer t hese addit ional ques tions.");
  254       }else  if(targetS ection ==  11){
  255           va r text = d ocument.cr eateTextNo de("Discla imer: Base d on your  answers in  Section B , you are  required t o answer t hese addit ional ques tions.");
  256       }
  257  
  258       paragr aph.append Child(text );
  259  
  260       cont.a ppendChild (close);
  261       cont.a ppendChild (paragraph );
  262       $('.fo rmContent' ).append(c ont);
  263   };
  264  
  265   //builds t he header  that displ ays inform ation abou t a study  and sectio n.
  266   function h eaderBuild er(targetS ection){
  267       var ap pTitle, id , section,  sectionCo ntainer, g enInfo, co mp;
  268  
  269       //Stud y title
  270       appTit le = docum ent.create Element("h 2");
  271       appTit le.setAttr ibute("cla ss", "appl icationTit le");
  272       
  273       //Sets  up the de fault stud y title in  the heade r
  274       if(stu dyTitle == = undefine d){
  275           va r text = d ocument.cr eateTextNo de("New IR B Applicat ion");
  276       }else{
  277           va r text = d ocument.cr eateTextNo de(studyTi tle);
  278       }
  279       appTit le.appendC hild(text) ;
  280  
  281       //Stud y ID
  282       id = d ocument.cr eateElemen t("small") ;
  283       
  284       //Sets  up the de fault stud y ID in th e header
  285       if(stu dyTitle == = undefine d){
  286           va r text = d ocument.cr eateTextNo de(" ID: T BD");
  287       }else{
  288           va r text = d ocument.cr eateTextNo de(" ID: "  + assigne dID);
  289       }
  290       id.app endChild(t ext);
  291       appTit le.appendC hild(id);
  292  
  293       $('div .page-head er').appen d(appTitle );
  294  
  295       //Curr ent Sectio n Display
  296       sectio n = docume nt.createE lement("h3 ");
  297       sectio n.setAttri bute("clas s", "secti onNumber") ;
  298       
  299       var se ctionTitle  = "ABCDEF GHIJKLMNOP QRSTUVWXYZ ";
  300       var te xt = docum ent.create TextNode(" Section "  + sectionT itle.charA t(targetSe ction));
  301       sectio n.appendCh ild(text);
  302       
  303       $('div .page-head er').appen d(section) ;
  304       
  305       //Gene ral Inform ation Disp lay
  306       sectio nContainer  = documen t.createEl ement("div ");
  307       sectio nContainer .setAttrib ute("class ", "sectio nContainer ");
  308  
  309       genInf o = docume nt.createE lement("h5 ");
  310       genInf o.setAttri bute("clas s", "secti onTitle");
  311  
  312       var te xt = docum ent.create TextNode(s tudy.form. containedF ormCollect ion[target Section].c ontainedFo rm.title);
  313       genInf o.appendCh ild(text);
  314       
  315       sectio nContainer .appendChi ld(genInfo );
  316       
  317       comp =  document. createElem ent("h5");
  318       comp.s etAttribut e("class",  "sectionL ocation");
  319       
  320       //Sett ing up a p laceholder  for compl etion stat us
  321       var te xt = docum ent.create TextNode(" Completed:  0/11");
  322       comp.a ppendChild (text);
  323  
  324       sectio nContainer .appendChi ld(comp);
  325  
  326       $('div .page-head er').appen d(sectionC ontainer);
  327   };
  328  
  329   //Creates  a general  warning to  display.  Takes in a  message a nd a warni ng type,
  330   //which wi ll move th e user to  the progre ss bar whe n called.
  331   function i nsertWarni ng(message , type){
  332       var wa rnCont, bo lded;
  333       
  334       //Remo ving any t races of p revious wa rnings.
  335       $('.al ert').remo ve();
  336  
  337       warnCo nt = docum ent.create Element("d iv");
  338       warnCo nt.setAttr ibute("cla ss", "aler t "+type);
  339       warnCo nt.setAttr ibute("rol e", "alert ");
  340  
  341       //Crea ting diffe rent conte nt based o n what is  requested
  342       bolded  = documen t.createEl ement("str ong");
  343       if(typ e == "aler t-warning" ){
  344           va r text = d ocument.cr eateTextNo de("Warnin g! ");
  345       }else  if(type ==  "alert-su ccess"){
  346           va r text = d ocument.cr eateTextNo de("Congra tulations!  ");
  347       }
  348       bolded .appendChi ld(text);
  349       warnCo nt.appendC hild(bolde d);
  350  
  351       //link ing everyt hing to th e page
  352       var te xt = docum ent.create TextNode(m essage);
  353       warnCo nt.appendC hild(text) ;
  354       
  355       //JQUE RY moving  page to th e generate d warning
  356       $('div .progress- container' ).prepend( warnCont);
  357       $('htm l, body'). animate({
  358                scrollTo p: $(docum ent).heigh t()
  359           },  1000);
  360   };
  361  
  362   //connects  to a rest  endpoint  and either  sends or
  363   //recieves  data
  364   function s endREST(ht tpMethod,  endpoint,  data, sync ){
  365       var xm lResponse;
  366       
  367       //acco unting for  internet  explorer's  needs
  368       if(win dow.XMLHtt pRequest){
  369           xm lResponse  = new XMLH ttpRequest ();
  370       }else{
  371           xm lResponse  = new Acti veXObject( "Microsoft .XMLHTTP") ;
  372       }
  373  
  374       try{
  375           // setting up  general h eaders
  376           xm lResponse. open(httpM ethod, res tPath.conc at(endpoin t), sync);
  377           xm lResponse. setRequest Header("Ca che-Contro l", "no-ca che");
  378           xm lResponse. setRequest Header("Co ntent-Type ", "applic ation/json ");
  379           xm lResponse. setRequest Header("Ac cept", "ap plication/ json");
  380           
  381           if ((httpMeth od == "PUT ")||(httpM ethod == " DELETE")){
  382                xmlRespo nse.setReq uestHeader ("sm_user" , data);
  383                xmlRespo nse.send(n ull);
  384                
  385                //204 is  the respo nse status  indicatin g success,  while
  386                //403 in dicates fa ilure
  387                if(xmlRe sponse.sta tus === 20 4){
  388                    retu rn true;
  389                }else if (xmlRespon se.status  === 403){
  390                    retu rn false;
  391                }
  392           }e lse if(htt pMethod ==  "POST"){
  393                try{
  394                    //se nding data  and alert ing the us er
  395                             xmlRes ponse.send (JSON.stri ngify(data ));
  396                    inse rtWarning( 'You have  successful ly saved y our respon ses', 'ale rt-success ');
  397                }catch(e ){
  398                    aler t(e.toStri ng());
  399                }
  400           }e lse if(htt pMethod ==  "GET"){
  401                //retrie ving the n eeded data
  402                xmlRespo nse.onread ystatechan ge = funct ion(){
  403                    if(x mlResponse .readyStat e === 4){
  404                         if(xmlResp onse.statu s === 200) {     
  405                             try{
  406                                  x mlResponse  = JSON.pa rse(xmlRes ponse.resp onseText);
  407                             }catch (e){
  408                                 al ert(e.toSt ring());
  409                             }        
  410                         }else{
  411                             if((xm lResponse. status !==  204) && ( xmlRespons e.status ! == 1223))
  412                              alert (xmlRespon se.status) ;
  413                         }
  414                    }
  415                };
  416                xmlRespo nse.send(n ull);
  417                //passin g the need ed data to  the funct ion that i s requesti ng it
  418                return x mlResponse ;
  419           }
  420  
  421       }catch (e){
  422               alert(e.t oString()) ;
  423       }
  424   };
  425  
  426   //Takes th e response  from the  database a nd builds  the questi ons displa yed
  427   //in the a pplication .
  428   function q uestionBui lder(secti on){
  429       //sett ing up a f resh set t o keep tra ck of ques tions that  have been
  430       //chan ged while  the user i s in a par ticular se ction.
  431       change dQuestions  = new Has hSet();
  432  
  433       //acco unting for  the JSON  format tha t is passe d by jaxb
  434       if(!(" length" in  section.c ontainedFo rm.formQue stionColle ction))
  435               section.c ontainedFo rm.formQue stionColle ction = [s ection.con tainedForm .formQuest ionCollect ion];
  436       
  437       //filt ering thro ugh each o f the ques tions in a  section t o build th em individ ually
  438       for(va r i=0; i<s ection.con tainedForm .formQuest ionCollect ion.length ; i++){
  439           va r form, fo rmGroup, t extLabel,  text, inpu t, toolSpa n, field,  legend;
  440           va r formQues tion = sec tion.conta inedForm.f ormQuestio nCollectio n[i];
  441  
  442           fo rm = docum ent.create Element("f orm");
  443           
  444           // div contai ning compl ete questi ons
  445           fo rmGroup =  document.c reateEleme nt("div");
  446           fo rmGroup.se tAttribute ("class",  "form-grou p");
  447                    
  448           // question t ext. We se e the intr odocution  of QID_ (Q uestion ID s) and lat er
  449       //we w ill see AI D_ (Answer  IDs). The se have be en put in  to comply  508 standa rds that 
  450       //inpu t id attri butes must  start wit h a letter .
  451           te xtLabel =  document.c reateEleme nt("label" );
  452           te xtLabel.se tAttribute ("for", "Q ID_" + for mQuestion. question.q uestionsID );
  453           
  454           te xt = docum ent.create TextNode(f ormQuestio n.question .questionH yperText);
  455           te xtLabel.ap pendChild( text);
  456  
  457           // tooltip lo gic
  458           if (formQuest ion.questi on.helpHyp erText){
  459                toolSpan  = documen t.createEl ement("spa n");
  460                toolSpan .setAttrib ute("data- toggle", f ormQuestio n.question .helpHyper Text);
  461                toolSpan .setAttrib ute("data- placement" , "right") ;
  462                toolSpan .setAttrib ute("title ", formQue stion.ques tion.helpH yperText);
  463                toolSpan .setAttrib ute("class ", "glyphi con glyphi con-questi on-sign");
  464           to olSpan.sty le.cursor  = "help";
  465           
  466                textLabe l.appendCh ild(toolSp an);
  467           }
  468           
  469           // Building t he questio ns based o n their ty pe: radio,  checkbox,  select, t extarea, f ile button , etc
  470           if ((formQues tion.quest ion.respon seFormat.n ame == "ra dio") || ( formQuesti on.questio n.response Format.nam e == "chec kbox")){
  471           // question i nput for r adios and  checkboxes
  472           fi eld = docu ment.creat eElement(" fieldset") ;
  473           le gend = doc ument.crea teElement( "legend");
  474           le gend.appen dChild(tex tLabel);
  475           fi eld.append Child(lege nd);
  476  
  477           if (!("length " in formQ uestion.qu estion.ans werCollect ion))
  478                      fo rmQuestion .question. answerColl ection = [ formQuesti on.questio n.answerCo llection];
  479                
  480           // building t he individ ual radio/ checkbox b uttons one  by one.
  481           fo r(var j=0;  j<formQue stion.ques tion.answe rCollectio n.length;  j++){
  482                    var  answerLabe l = docume nt.createE lement("la bel");
  483                             
  484                    //ra dio button  formattin g based on  the lengt h of text  associated  with the  radio butt on.
  485                    if(( formQuesti on.questio n.response Format.nam e == "radi o") && (fo rmQuestion .question. answerColl ection[j]. value.leng th < 6)){
  486                         answerLabe l.setAttri bute("clas s", "radio -inline");
  487                    }els e if((form Question.q uestion.re sponseForm at.name ==  "radio")  && (formQu estion.que stion.answ erCollecti on[j].valu e.length > = 6)){
  488                         answerLabe l.setAttri bute("clas s", "radio ");
  489                    }els e if(formQ uestion.qu estion.res ponseForma t.name ==  "checkbox" ){
  490                         answerLabe l.setAttri bute("clas s", "check box");
  491                    }
  492                answerLa bel.setAtt ribute("fo r", "AID_"  + formQue stion.ques tion.answe rCollectio n[j].answe rsID);
  493                    
  494                //puttin g together  general s tructure
  495                    var  input = do cument.cre ateElement ("input");
  496                    inpu t.setAttri bute("type ", formQue stion.ques tion.respo nseFormat. name);
  497                    inpu t.setAttri bute("name ", "QID_"  + formQues tion.quest ion.questi onsID);
  498                    inpu t.setAttri bute("id",  "AID_" +  formQuesti on.questio n.answerCo llection[j ].answersI D);
  499  
  500                //disabl ing questi ons if the  study is  in review
  501                if(recen tStage ==  "2"){
  502                    inpu t.setAttri bute("disa bled", tru e);
  503                }
  504  
  505                //Specif ying the m ethod to n otify whic h question s are chan ged. This  method hel ps group r adio butto ns
  506                //togeth er, while  allowing c heckboxes  to be save d individu ally. 
  507                    if(f ormQuestio n.question .responseF ormat.name  == "check box"){
  508                         input.setA ttribute(" title", fo rmQuestion .question. answerColl ection[j]. sequencePo sition);
  509                         input.setA ttribute(" onchange",  "Function (changedQu estions.ad d("+formQu estion.que stion.answ erCollecti on[j].answ ersID+"))" );
  510                    }els e{
  511                         input.setA ttribute(" onchange",  "Function (changedQu estions.ad d("+formQu estion.que stion.ques tionsID+") )");
  512                    }
  513                    if(( rollup.que stionRespo nseUpdates  === undef ined) || ( rollup.que stionRespo nseUpdates .responses  === undef ined)){
  514                        
  515                    }els e{
  516                         //looking  for user's  responses  that have  been grab bed from t he databas e and upda ting quest ions.
  517                         for(var x= 0; x<rollu p.question ResponseUp dates.resp onses.leng th; x++){
  518                                      if((roll up.questio nResponseU pdates.res ponses[x]. questionsI D == formQ uestion.qu estion.que stionsID)  && (rollup .questionR esponseUpd ates.respo nses[x].an swersID) = = formQues tion.quest ion.answer Collection [j].answer sID){
  519                                          inpu t.checked  = true;
  520                                      }
  521                         }
  522                    }
  523                    
  524                    var  value = do cument.cre ateTextNod e(formQues tion.quest ion.answer Collection [j].value) ;
  525                    
  526                    answ erLabel.ap pendChild( input);
  527                    answ erLabel.ap pendChild( value);
  528                    
  529                    fiel d.appendCh ild(answer Label);
  530                formGrou p.appendCh ild(field) ;
  531                form.app endChild(f ormGroup);
  532                    $('d iv.formCon tent').app end(form);
  533                }
  534           }e lse if(for mQuestion. question.r esponseFor mat.name = = "select" ){
  535                formGrou p.appendCh ild(textLa bel);
  536                form.set Attribute( "role", "f orm")
  537                form.app endChild(f ormGroup);
  538                
  539           // setting up  the gener al structu re of a dr op down
  540                input =  document.c reateEleme nt("select ");
  541                var inpu tOption =  document.c reateEleme nt("option ");
  542                inputOpt ion.setAtt ribute("va lue", "non e");
  543                var text  = documen t.createTe xtNode("no ne");
  544                inputOpt ion.append Child(text );
  545                input.ap pendChild( inputOptio n);
  546  
  547           // populating  drop down  based on  users grab bed from t he databas e
  548           fo r(var j=0;  j<users.u ser.length ; j++){
  549                inputOpt ion = docu ment.creat eElement(" option");
  550                inputOpt ion.setAtt ribute("va lue", user s.user[j]. loginName) ;
  551                text = d ocument.cr eateTextNo de(users.u ser[j].log inName);
  552                inputOpt ion.append Child(text );
  553                input.ap pendChild( inputOptio n);
  554           }
  555  
  556                input.se tAttribute ("name", " QID_" + fo rmQuestion .question. questionsI D);
  557                input.se tAttribute ("class",  "form-cont rol normal  select");
  558           in put.setAtt ribute("on click", "c hangedQues tions.add( "+formQues tion.quest ion.questi onsID+")") ;
  559           
  560           // disabling  question i f the stud y is in re view
  561           if (recentSta ge == "2") {
  562                input.se tAttribute ("disabled ", true);
  563           }
  564  
  565                formGrou p.appendCh ild(input) ;
  566                $('div.f ormContent ').append( form);
  567  
  568           if ((rollup.q uestionRes ponseUpdat es === und efined) ||  (rollup.q uestionRes ponseUpdat es.respons es === und efined)){
  569           }e lse{
  570                //changi ng which o ption in t he dropdow n is initi ally selec ted
  571                for(var  x=0; x<rol lup.questi onResponse Updates.re sponses.le ngth; x++) {
  572                    if(r ollup.ques tionRespon seUpdates. responses[ x].questio nsID == fo rmQuestion .question. questionsI D){
  573                    inpu t.value =  rollup.que stionRespo nseUpdates .responses [x].respon se;
  574                    
  575                    stud yPI.put(fo rmQuestion .question. questionsI D, rollup. questionRe sponseUpda tes.respon ses[x].res ponse);
  576                    }
  577                }   
  578           }
  579  
  580           }e lse if((fo rmQuestion .question. responseFo rmat.name  == "button ")&&(recen tStage !=  "2")){
  581  
  582                var uplo adInput, u ploadLink,  uploadIco n;
  583           va r noFile =  true;
  584                
  585                formGrou p.appendCh ild(textLa bel);
  586                
  587           // setting up  the gener al structu re for a f ile upload  button
  588                form.set Attribute( "role", "f orm");
  589  
  590           // setting up  the uploa d button
  591           up loadInput  = document .createEle ment("inpu t");
  592           up loadInput. setAttribu te("id", " upload");
  593           up loadInput. setAttribu te("name",  "QID_" +  formQuesti on.questio n.question sID);
  594           up loadInput. setAttribu te("type",  "file");
  595  
  596           // attaching  the upload  button
  597           fo rmGroup.ap pendChild( uploadInpu t);
  598                
  599           if ((rollup.q uestionRes ponseUpdat es === und efined) ||  (rollup.q uestionRes ponseUpdat es.respons es === und efined)){
  600           }e lse{
  601           // looking fo r response s to popul ate the te xtarea wit h
  602                for(var  x=0; x<rol lup.questi onResponse Updates.re sponses.le ngth; x++) {
  603                    if(r ollup.ques tionRespon seUpdates. responses[ x].questio nsID == fo rmQuestion .question. questionsI D){
  604                    var  text = doc ument.crea teTextNode ("Uploaded  File: " +  rollup.qu estionResp onseUpdate s.response s[x].respo nse);
  605                    form Group.appe ndChild(te xt);
  606                    uplo adInput.se tAttribute ("disabled ", "disabl ed");
  607                    }
  608                }
  609           }
  610  
  611                form.app endChild(f ormGroup);
  612                $('div.f ormContent ').append( form);
  613           
  614           }e lse{
  615                //questi on input f or everyth ing else,  which shou ld cover t extares. 
  616                formGrou p.appendCh ild(textLa bel);
  617                form.set Attribute( "role", "f orm");
  618                form.app endChild(f ormGroup);
  619  
  620           // setting up  the gener al structu re for a t extarea
  621           if (formQuest ion.questi on.respons eFormat.na me == "tex tarea"){
  622                input =  document.c reateEleme nt("textar ea");
  623                input.se tAttribute ("rows", " 10");
  624           }e lse{
  625                input =  document.c reateEleme nt("input" );
  626                input.se tAttribute ("type", f ormQuestio n.question .responseF ormat.name );
  627           }
  628  
  629           // setting up  the gener al structu re for a t extarea
  630                input.se tAttribute ("name", " QID_" + fo rmQuestion .question. questionsI D);
  631                input.se tAttribute ("class",  "form-cont rol normal ");
  632                input.se tAttribute ("onchange ", "Functi on(changed Questions. add("+form Question.q uestion.qu estionsID+ "))");
  633                
  634           // making sur e the text area is di sabled if  the applic ation is i n review
  635           if (recentSta ge == "2") {
  636                input.se tAttribute ("disabled ", true);
  637           }
  638  
  639                if((roll up.questio nResponseU pdates ===  undefined ) || (roll up.questio nResponseU pdates.res ponses ===  undefined )){
  640                }else{
  641                    //lo oking for  responses  to populat e the text area with
  642                    for( var x=0; x <rollup.qu estionResp onseUpdate s.response s.length;  x++){
  643                         if(rollup. questionRe sponseUpda tes.respon ses[x].que stionsID = = formQues tion.quest ion.questi onsID){
  644                             input. value = ro llup.quest ionRespons eUpdates.r esponses[x ].response ;
  645                         }
  646                    }
  647                }
  648  
  649                formGrou p.appendCh ild(input) ;
  650                $('div.f ormContent ').append( form);
  651                
  652           }
  653  
  654           // checking t o see if t he questio n has a de pendency o n another  answer
  655           if ((formQues tion.requi redPredece ssorAnswer sID)&&(rec entStage ! = "2")){      
  656           qu estionRequ irement(fo rmQuestion , input);
  657           }
  658  
  659       //maki ng sure th e question  is comple tely disab led if the  applicati on is in r eview
  660       if(rec entStage = = "2"){
  661           in put.setAtt ribute("di sabled", t rue);
  662       }
  663  
  664       }
  665   };
  666  
  667   //checks t o see if t here are a ny unsaved  questions  within
  668   //a sectio n and noti fies the u ser when t hey try to  change se ctions
  669   function c heckSave(t argetSecti on){
  670       if(cha ngedQuesti ons.isEmpt y()){
  671               sectionBu ilder(targ etSection) ;
  672       }else{
  673           if ($('.alert -warning') .length !=  0){
  674                sectionB uilder(tar getSection );
  675           }e lse{
  676                insertWa rning("You  have unsa ved respon ses. Pleas e click th e Save Pro gress butt on at the  bottom of  the page o r your cha nges will  be lost.",  "alert-wa rning");
  677           }
  678       }
  679   }
  680  
  681   //some que stions are  optional,  this goes  through t he optiona l question s and
  682   //sets up  the proper  dependenc ies on the  front end  to allow  for instan t activati on
  683   //and deac tivation o f question s.
  684   function q uestionReq uirement(f ormQuestio n, input){
  685      
  686       //gene ral querie s to grab  parent que stion
  687       var pa rentAnswer  = $('#AID _'+formQue stion.requ iredPredec essorAnswe rsID);
  688       var ra dioPair;
  689       
  690       //chec kboxes hav e a listen er on the  one checkb ox, but ra dios need 
  691       //list ener to tu rn on the  question a nd a liste ner to tur n off the  question.
  692       //this  requires  us to quer y the yes/ no radio b uttons and  attach a  listener t o each.
  693       if(par entAnswer. attr("type ")=="check box"){
  694           if (!(parentA nswer.attr ('onclick' )))
  695                parentAn swer.attr( "onclick",  "activate Question(" +formQuest ion.requir edPredeces sorAnswers ID+")");
  696       }else  if(parentA nswer.attr ("type")== "radio"){
  697           ra dioPair =  $('[name=" '+($('#AID _'+formQue stion.requ iredPredec essorAnswe rsID).attr ("name"))+ '"]');
  698           if (!(radioPa ir.attr('o nclick'))) {
  699                for(var  j=0; j<rad ioPair.len gth; j++){
  700                    radi oPair[j].s etAttribut e("onclick ", "activa teQuestion ("+formQue stion.requ iredPredec essorAnswe rsID+")");
  701                }
  702           }e lse{
  703                var mult ipleDepend ency = tru e;
  704               
  705                for(var  j=0; j<rad ioPair.len gth; j++){
  706                    var  lookupID =  parseInt( radioPair[ j].getAttr ibute("id" ));
  707                    //ch ecking to  see if rad io buttons  in the sa me questio n
  708                    //ha ve differe nt depende ncies. 
  709                    if(( dependency .containsK ey(lookupI D))  ){
  710                         if(lookupI D != formQ uestion.re quiredPred ecessorAns wersID){
  711                             
  712                             //buil ding the c onsolodate d string o f IDs that  need to b e updated
  713                             var ch angeString , activate String;
  714                             activa teString =  "Function (";
  715                             for(va r x=0; x<r adioPair.l ength; x++ ){
  716                                 va r secondLo okup = par seInt(radi oPair[x].g etAttribut e("id"));
  717                                 ac tivateStri ng += "act ivateQuest ion(" + se condLookup  + ")";
  718                             }
  719                             activa teString + = ")";
  720                             activa teString =  activateS tring.repl ace(")a",  "),a");
  721                             
  722                             //upda ting the a ctivation  attribute
  723                             for(va r x=0; x<r adioPair.l ength; x++ ){
  724                                 ra dioPair[x] .setAttrib ute("oncli ck", activ ateString) ;
  725                             }
  726                         }
  727                    }els e{
  728                         multipleDe pendency =  false;
  729                    }
  730                }
  731           }
  732       }
  733       
  734       //We w ant to mak e sure tha t all chil dren are d isabled wh en their p arents are  disabled.
  735       if(par entAnswer. attr("disa bled") ==  "disabled" ){
  736           $( '[name = " QID_'+form Question.q uestion.qu estionsID+ '"]').attr ("disabled ", true);
  737       }
  738  
  739       //Belo w we set u p a data s tructure t o hold par ent/child  relationsh ips. This  includes s etting up
  740       //a ha sh map whe re they ke y is a que stion ID a nd the val ue is a se t of quest ion IDs th at the key  effects
  741  
  742       //chec king to se e if there  is alread y an estab lished key  for this  answer
  743       if(dep endency.co ntainsKey( formQuesti on.require dPredecess orAnswersI D)){
  744           
  745           // checking t o see if t he parent  answer is  checked or  not, whic h directly  affects w hether the  child is  active/dea ctive
  746           if ( (!(paren tAnswer.is (':checked '))) && (! (rollupAns wers.conta ins(formQu estion.req uiredPrede cessorAnsw ersID))) )  {
  747                if((inpu t.getAttri bute("type ") == "rad io") ||(in put.getAtt ribute("ty pe") == "c heckbox")) {
  748                    $('[ name="QID_ '+formQues tion.quest ion.questi onsID+'"]' ).attr("di sabled", t rue);
  749                }else{ 
  750                    inpu t.setAttri bute("disa bled",true );
  751                }
  752  
  753                //points  to an off  page depe ndency. In  this case  we remove  the quest ion comple tely.
  754                if((!(ro llupAnswer s.contains (formQuest ion.requir edPredeces sorAnswers ID))) && ( $('#AID_'+ formQuesti on.require dPredecess orAnswersI D).length  == 0)){
  755                    $('[ name="QID_ '+formQues tion.quest ion.questi onsID+'"]' ).parent() .parent(). hide();
  756                }
  757  
  758           }
  759           
  760           // adding id  to the set  of questi ons affect ed by an a nswer.
  761           if (!(depende ncy.get(fo rmQuestion .requiredP redecessor AnswersID) ).contains (formQuest ion.questi on.questio nsID)){
  762                (depende ncy.get(fo rmQuestion .requiredP redecessor AnswersID) ).add(form Question.q uestion.qu estionsID) ;
  763           }
  764           
  765       }else{
  766           // instantiat ing the an swer in th e dependen cy map and  giving it  a set of  questions  it affects
  767           // Going thro ugh the sa me logic a s above.
  768           va r temp = n ew HashSet ();
  769           te mp.add(for mQuestion. question.q uestionsID );
  770           de pendency.p ut(formQue stion.requ iredPredec essorAnswe rsID, temp );
  771  
  772           if ( (!(paren tAnswer.is (':checked '))) && (! (rollupAns wers.conta ins(formQu estion.req uiredPrede cessorAnsw ersID))) )  {
  773                if((inpu t.getAttri bute("type ") == "rad io") || (i nput.getAt tribute("t ype") == " checkbox") ){
  774                    $('[ name="QID_ '+formQues tion.quest ion.questi onsID+'"]' ).attr("di sabled", t rue);
  775                }else{
  776                    inpu t.setAttri bute("disa bled",true );
  777                }
  778  
  779                if((!(ro llupAnswer s.contains (formQuest ion.requir edPredeces sorAnswers ID))) && ( $('#AID_'+ formQuesti on.require dPredecess orAnswersI D).length  == 0)){
  780                    $('[ name="QID_ '+formQues tion.quest ion.questi onsID+'"]' ).parent() .parent(). hide();
  781                }
  782           }
  783       }
  784   };
  785  
  786   //This fun ction togg les if a q uestion is  activated  or
  787   //deactiva ted.
  788   function a ctivateQue stion(answ ersId){
  789       var se t = (depen dency.get( answersId) ).values() ;
  790       
  791       if(rec entStage ! = "2"){
  792           fo r(var i=0;  i<set.len gth; i++){
  793                if($('#A ID_'+answe rsId).attr ("disabled ")){
  794                    $('[ name="QID_ '+set[i]+' "]').attr( "disabled" , true);
  795                }else{
  796                    if(! ($('#AID_' +answersId ).is(':che cked'))){
  797                            $('[nam e="QID_'+s et[i]+'"]' ).attr("di sabled", t rue);
  798                       } else{
  799                            $('[nam e="QID_'+s et[i]+'"]' ).attr("di sabled", f alse);
  800                       }  
  801               }   
  802               //recursi vely going  through t he quetion s to activ ate/deacti vate child ren
  803               var setQu estions =  $('[name=" QID_'+set[ i]+'"]');
  804                for(var  j=0; j<set Questions. length; j+ +){
  805                    var  setID = se tQuestions [j].getAtt ribute("id ");
  806                    if(d ependency. containsKe y(parseInt (setID))){
  807                         activateQu estion(par seInt(setI D));
  808                    }
  809               }
  810           }
  811       }
  812   };
  813  
  814   //Builds t he buttons  that appe ar at the  bottom of  the page 
  815   function p rogressBui lder(targe tSection){
  816       var sp Button;
  817  
  818       //Canc el Button.  Takes the  user back  to the ho me page.
  819       csButt on = docum ent.create Element("b utton");
  820       csButt on.setAttr ibute("val ue", "Canc el");
  821       csButt on.setAttr ibute("typ e", "butto n");
  822       csButt on.setAttr ibute("cla ss", "btn  btn-defaul t pull-lef t");
  823       csButt on.setAttr ibute("tit le", "Canc el");
  824       csButt on.setAttr ibute("onc lick", "lo cation.hre f='../Site Pages/Home .aspx'");
  825  
  826       var te xt = docum ent.create TextNode(" Cancel");
  827       csButt on.appendC hild(text) ;
  828       $('div .progress- container' ).append(c sButton);
  829  
  830       //save  progress  button. Ru ns the fun ction to p ackage the  user's re sponses.
  831       spButt on = docum ent.create Element("b utton");
  832       spButt on.setAttr ibute("val ue", "Save  Progress" );
  833       spButt on.setAttr ibute("typ e", "butto n");
  834       spButt on.setAttr ibute("cla ss", "btn  btn-defaul t pull-rig ht");
  835       spButt on.setAttr ibute("tit le", "Save  Progress" );
  836       spButt on.setAttr ibute("onc lick", "cr eateRespon ses()");
  837  
  838       var te xt = docum ent.create TextNode(" Save Progr ess");
  839       
  840       spButt on.appendC hild(text) ;
  841       $('div .progress- container' ).append(s pButton);
  842   };
  843  
  844   //Builds t he buttons  that appe ar on top  of the sid ebar which
  845   //allow us ers to upl oad docume nts and pr int a sect ion
  846   function a ctionBarBu ilder(targ etSection) {
  847       var ac tionTools,  printList , printLin k, printIc on;
  848       var up loadList,  uploadLink , uploadIc on, upload Input;
  849       var se ctionTitle  = "ABCDEF GHIJKLMNOP QRSTUVWXYZ ";    
  850  
  851       //gene ral struct ure for pr int button
  852       action Tools = do cument.cre ateElement ("ul");
  853       action Tools.setA ttribute(" class", "a ctionTools ");
  854  
  855       printL ist = docu ment.creat eElement(" li");
  856       
  857       //href  will prin t the curr ent webpag e
  858       printL ink = docu ment.creat eElement(" a");
  859       printL ink.setAtt ribute("hr ef", "java script:win dow.print( )");
  860       printL ink.setAtt ribute("ti tle", "");
  861  
  862       printI con = docu ment.creat eElement(" span");
  863       printI con.setAtt ribute("cl ass", "gly phicon gly phicon-pri nt");
  864       printL ink.append Child(prin tIcon);
  865  
  866       var te xt = docum ent.create TextNode(" Print Sect ion " + se ctionTitle .charAt(ta rgetSectio n));
  867       printL ink.append Child(text );
  868  
  869       printL ist.append Child(prin tLink);
  870       action Tools.appe ndChild(pr intList);
  871  
  872       //gene ral struct ure for up load butto n
  873       //crea ting the n ormal butt on that st ays hidden
  874       upload Input = do cument.cre ateElement ("input");
  875       upload Input.setA ttribute(" id", "uplo ad-general ");
  876       upload Input.setA ttribute(" type", "fi le");
  877       upload Input.setA ttribute(" name", "00 00");
  878       upload Input.styl e.display  = "none";
  879       action Tools.appe ndChild(up loadInput) ;
  880  
  881       upload List = doc ument.crea teElement( "li");
  882  
  883       //sett ing up the  stylized  button tha t triggers  the usual
  884       //file  upload bu tton which  is hidden .
  885       upload Link = doc ument.crea teElement( "a");
  886       upload Link.setAt tribute("h ref", "#") ;
  887       upload Link.setAt tribute("o nclick", " Function($ ('#upload- general'). trigger('c lick'), ch angedQuest ions.add(' 0000'))");
  888  
  889       upload Link.style .cursor =  "pointer";
  890       
  891       upload Icon = doc ument.crea teElement( "span");
  892       upload Icon.setAt tribute("c lass", "gl yphicon gl yphicon-up load");
  893       upload Link.appen dChild(upl oadIcon);
  894  
  895       var te xt = docum ent.create TextNode(" Upload Doc ument(s)") ;
  896       upload Link.appen dChild(tex t);
  897  
  898       upload List.appen dChild(upl oadLink);
  899       action Tools.appe ndChild(up loadList);
  900       
  901  
  902       $('div .actionbar ').append( actionTool s);
  903   };
  904  
  905   //creates  the rest o f the side bar includ ing the se ctions
  906   //and the  buttons th at allow y ou to revi ew and sub mit
  907   function w ellSidebar Builder(ta rgetSectio n){
  908       var li stGroup, l Group;
  909           
  910       $('.li st-group') .remove();
  911  
  912       listGr oup = docu ment.creat eElement(" div");
  913       listGr oup.setAtt ribute("cl ass", "lis t-group");
  914  
  915       //crea ting the s idebar men u button f or each se ction
  916       for(va r i=0; i<s tudy.form. containedF ormCollect ion.length ; i++){
  917           va r link = d ocument.cr eateElemen t("a");
  918           li nk.style.c ursor = "p ointer";
  919  
  920           // setting up  the activ ated secti on styling
  921           if (i == targ etSection) {
  922                link.set Attribute( "class", " list-group -item acti ve");
  923           }e lse{
  924                link.set Attribute( "class", " list-group -item");
  925           }
  926           
  927           va r sectionT itle = "AB CDEFGHIJKL MNOPQRSTUV WXYZ";
  928  
  929           va r text = d ocument.cr eateTextNo de("Sectio n " + sect ionTitle.c harAt(i));
  930           li nk.appendC hild(text) ;
  931           
  932           li stGroup.ap pendChild( link);
  933       }
  934       
  935       $('div .well.side bar').appe nd(listGro up);
  936  
  937       lGroup  = documen t.createEl ement("div ");
  938       lGroup .setAttrib ute("class ", "list-g roup");
  939  
  940       //sett ing up the  Attachmen ts button
  941       var li nk = docum ent.create Element("a ");
  942       link.s tyle.curso r = "point er";
  943       link.s etAttribut e("class",  "list-gro up-item");
  944       
  945       var te xt = docum ent.create TextNode(" Attachment s");
  946       link.a ppendChild (text);
  947       
  948       var ic on = docum ent.create Element("s pan");
  949       icon.s etAttribut e("class",  "badge");
  950       
  951       var te xt = docum ent.create TextNode(" 0");
  952       icon.a ppendChild (text);
  953  
  954       link.a ppendChild (icon);
  955  
  956       lGroup .appendChi ld(link);
  957  
  958       //sett ing up the  Review &  Submit but ton
  959       var li nk = docum ent.create Element("a ");
  960       link.s tyle.curso r = "point er";
  961       link.s etAttribut e("class",  "list-gro up-item");
  962       link.s etAttribut e("onclick ", "review App()");
  963       
  964       var te xt = docum ent.create TextNode(" Review & S ubmit");
  965       link.a ppendChild (text);
  966       
  967       var ic on = docum ent.create Element("s pan");
  968       icon.s etAttribut e("class",  "glyphico n glyphico n-chevron- right");
  969       
  970       link.a ppendChild (icon);
  971  
  972       lGroup .appendChi ld(link);
  973  
  974       $('div .well.side bar').appe nd(lGroup) ;
  975       
  976       //upda ting sideb ar icons
  977       update SidebarIco ns(targetS ection);
  978   };
  979  
  980   //organize s question s in secti ons to be  either ans wered or u nanswered  and then
  981   //reports  to the use r which qu estions th ey still n eed to fil l out.
  982   function v alidateQue stions(){
  983       
  984       formsR esponse =  study;
  985       rollup Response =  rollup;
  986       
  987       var fo rm_id_ques tions_id_m ap = {};
  988       var qu estions_pr edecessor_ map = {};
  989       var fo rmValidCon t, section Cont, ques tionCont,  text, anch or;
  990       var fo rmTable, r ow, questi onTable;
  991  
  992       formTa ble = docu ment.creat eElement(" table");
  993       questi onTable =  document.c reateEleme nt("table" );
  994  
  995       //putt ing togeth er a map o f parent/c hild quest ions
  996       for (v ar x = 0;  x < formsR esponse.fo rm.contain edFormColl ection.len gth;x++) {
  997           fo r(var xx =  0; xx < f ormsRespon se.form.co ntainedFor mCollectio n[x].conta inedForm.f ormQuestio nCollectio n.length;  xx++){
  998                if (form sResponse. form.conta inedFormCo llection[x ].containe dForm.form sID in for m_id_quest ions_id_ma p) {
  999                      fo rm_id_ques tions_id_m ap[formsRe sponse.for m.containe dFormColle ction[x].c ontainedFo rm.formsID ].push(for msResponse .form.cont ainedFormC ollection[ x].contain edForm.for mQuestionC ollection[ xx].questi on.questio nsID)
  1000                    }els e form_id_ questions_ id_map[for msResponse .form.cont ainedFormC ollection[ x].contain edForm.for msID] = [  formsRespo nse.form.c ontainedFo rmCollecti on[x].cont ainedForm. formQuesti onCollecti on[xx].que stion.ques tionsID    ]; 
  1001                
  1002                if (form sResponse. form.conta inedFormCo llection[x ].containe dForm.form QuestionCo llection[x x].require dPredecess orAnswersI D) {
  1003                    ques tions_pred ecessor_ma p[formsRes ponse.form .contained FormCollec tion[x].co ntainedFor m.formQues tionCollec tion[xx].q uestion.qu estionsID]  = formsRe sponse.for m.containe dFormColle ction[x].c ontainedFo rm.formQue stionColle ction[xx]. requiredPr edecessorA nswersID;
  1004                }
  1005           }
  1006       }
  1007  
  1008       var fo rm_id_empt y = [];
  1009       var fo rm_id_inco mplete = [ ];
  1010       
  1011       var se ctionTitle  = "ABCDEF GHIJKLMNOP QRSTUVWXYZ ";
  1012       formVa lidCont =  document.c reateEleme nt("div");
  1013       sectio nCont = do cument.cre ateElement ("div");
  1014  
  1015       //grab bing quest ions that  still need  to be ans wered
  1016       for(va r x = 0; x <rollupRes ponse.ques tionRespon seUpdates. formValida tionReport .formStatu sCollectio n.length;  x++){
  1017                    
  1018           if (rollupRes ponse.ques tionRespon seUpdates. formValida tionReport .formStatu sCollectio n[x].statu s==="INCOM PLETE"){
  1019                form_id_ incomplete .push(roll upResponse .questionR esponseUpd ates.formV alidationR eport.form StatusColl ection[x]. formsID);
  1020           
  1021           }e lse if(rol lupRespons e.question ResponseUp dates.form Validation Report.for mStatusCol lection[x] .status=== "EMPTY"){
  1022                form_id_ empty.push (rollupRes ponse.ques tionRespon seUpdates. formValida tionReport .formStatu sCollectio n[x].forms ID);
  1023                //notify ing users  of section s that are  completel y empty
  1024                row = do cument.cre ateElement ("tr");
  1025                row.appe ndChild(cr eateCell(" td", "Sect ion " +sec tionTitle. charAt(x)+  ": " + st udy.form.c ontainedFo rmCollecti on[x].cont ainedForm. title + "  is empty",  null));
  1026                formTabl e.appendCh ild(row);
  1027           }
  1028       }
  1029  
  1030       formVa lidCont.ap pendChild( formTable) ;
  1031       
  1032       //belo w we grab  questions  that have  been answe red
  1033       var fi lled_quest ions = [];
  1034  
  1035       for(va r x = 0; x <rollupRes ponse.ques tionRespon seUpdates. responses. length; x+ +){
  1036               filled_qu estions.pu sh(rollupR esponse.qu estionResp onseUpdate s.response s[x].quest ionsID);
  1037       }
  1038  
  1039       var fi lled_answe rs = [];
  1040  
  1041       for(va r x = 0; x <rollupRes ponse.ques tionRespon seUpdates. responses. length; x+ +){
  1042           if (rollupRes ponse.ques tionRespon seUpdates. responses[ x].answers ID)
  1043                filled_a nswers.pus h(rollupRe sponse.que stionRespo nseUpdates .responses [x].answer sID);
  1044       }
  1045       
  1046       functi on hasPred ecessorAns wered(ques tion){
  1047           if  (filled_a nswers.ind exOf(quest ions_prede cessor_map [question] ) == -1){
  1048                return f alse;
  1049           }e lse{
  1050                return t rue;
  1051           }
  1052       };
  1053       
  1054       var in complete_f orms_quest ions_map =  {};
  1055  
  1056       //putt ing togeth er a map o f incomple te section s as the k ey and una nswered qu estions an d the valu es
  1057       for(va r x = 0; x  < form_id _incomplet e.length;  x++){
  1058           fo r(var xx =  0; xx < f orm_id_que stions_id_ map[form_i d_incomple te[x]].len gth; xx++) {
  1059                if(fille d_question s.indexOf( form_id_qu estions_id _map[form_ id_incompl ete[x]][xx ])==-1){
  1060                             if(!(  form_id_qu estions_id _map[form_ id_incompl ete[x]][xx ] in quest ions_prede cessor_map  )){
  1061                                 if  ( form_id _incomplet e[x] in in complete_f orms_quest ions_map )  {
  1062                                       incompl ete_forms_ questions_ map[form_i d_incomple te[x]].pus h(form_id_ questions_ id_map[for m_id_incom plete[x]][ xx]);
  1063                                 }e lse {
  1064                                       incompl ete_forms_ questions_ map[form_i d_incomple te[x]] = [  form_id_q uestions_i d_map[form _id_incomp lete[x]][x x] ];
  1065                                 }
  1066                             }else  {
  1067                                 if (hasPredec essorAnswe red(form_i d_question s_id_map[f orm_id_inc omplete[x] ][xx])){
  1068                                      if ( for m_id_incom plete[x] i n incomple te_forms_q uestions_m ap ) {
  1069                                          inco mplete_for ms_questio ns_map[for m_id_incom plete[x]]. push(form_ id_questio ns_id_map[ form_id_in complete[x ]][xx]);
  1070                                      }else {
  1071                                                incomplet e_forms_qu estions_ma p[form_id_ incomplete [x]] = [ f orm_id_que stions_id_ map[form_i d_incomple te[x]][xx]  ];
  1072                             }
  1073                                 } 
  1074                             }
  1075                }
  1076           }
  1077       }
  1078  
  1079       //goin g through  the map th at was jus t created  to notify  the users  of what sp ecific que stions sti ll need to  be answer ed.
  1080       for(va r x=0; x<s tudy.form. containedF ormCollect ion.length ; x++){
  1081           fo r(var i=0;  i<form_id _incomplet e.length;  i++){
  1082                if(form_ id_incompl ete[i] ==  study.form .contained FormCollec tion[x].co ntainedFor m.formsID) {
  1083                             for(va r y=0; y<s tudy.form. containedF ormCollect ion[x].con tainedForm .formQuest ionCollect ion.length ; y++){
  1084                         for(var ke y in incom plete_form s_question s_map){
  1085                                 fo r(var j=0;  j<incompl ete_forms_ questions_ map[key].l ength; j++ ){
  1086                                               if(incompl ete_forms_ questions_ map[key][j ] == study .form.cont ainedFormC ollection[ x].contain edForm.for mQuestionC ollection[ y].questio n.question sID){
  1087                                      row = do cument.cre ateElement ("tr");
  1088                                                   row.ap pendChild( createCell ("td", "In  Section "  +sectionT itle.charA t(x)+ ", y ou still n eed to ans wer: " + s tudy.form. containedF ormCollect ion[x].con tainedForm .formQuest ionCollect ion[y].que stion.ques tionHyperT ext, null) );
  1089                                                   questi onTable.ap pendChild( row);
  1090                                 }
  1091                                 }
  1092                         }
  1093                             }
  1094                }
  1095           }
  1096       }
  1097  
  1098       formVa lidCont.ap pendChild( questionTa ble);
  1099  
  1100       //reve aling the  buttons to  generate  the hipaa  and consen t form.
  1101       if((ro llupRespon se.questio nResponseU pdates.for mValidatio nReport.fo rmStatusCo llection[1 2].status! =="EMPTY")  || (rollu pResponse. questionRe sponseUpda tes.formVa lidationRe port.formS tatusColle ction[13]. status!==" EMPTY")){
  1102           // putting to gether the  hipaa for m button
  1103           if (rollupRes ponse.ques tionRespon seUpdates. formValida tionReport .formStatu sCollectio n[12].stat us!=="EMPT Y"){
  1104  
  1105                var gene rate = doc ument.crea teElement( "button");
  1106                generate .setAttrib ute("oncli ck", "gene rateHipaa( '15')");
  1107                var text  = documen t.createTe xtNode("Ge nerate HIP AA");
  1108                generate .appendChi ld(text);
  1109                formVali dCont.appe ndChild(ge nerate);
  1110           }
  1111  
  1112           // putting to gether the  consent f orm button
  1113           if (rollupRes ponse.ques tionRespon seUpdates. formValida tionReport .formStatu sCollectio n[13].stat us!=="EMPT Y"){
  1114  
  1115                var gene rate = doc ument.crea teElement( "button");
  1116                generate .setAttrib ute("oncli ck", "gene rateHipaa( '14')");
  1117                var text  = documen t.createTe xtNode("Ge nerate ICF ");
  1118                generate .appendChi ld(text);
  1119                formVali dCont.appe ndChild(ge nerate);
  1120           }
  1121  
  1122       }else{
  1123                //hintin g to the u sers that  they still  need to c omplete th e hipaa an d consent  form
  1124                var brea ker = docu ment.creat eElement(" br");
  1125                formVali dCont.appe ndChild(br eaker);
  1126  
  1127                var para graph = do cument.cre ateElement ("p");
  1128                var text  = documen t.createTe xtNode("Wh en you hav e complete d both the  HIPAA and  ICF secti ons, you m ay generat e document s.");
  1129                paragrap h.appendCh ild(text);
  1130                formVali dCont.appe ndChild(pa ragraph);
  1131       }
  1132  
  1133       //chec king the c ompletenes s of the a pplication . All of t he section s have to  be labled  as complet e
  1134       var co mplete = t rue;
  1135       var ex pedited_co mplete = t rue;
  1136       for(va r x=0; x<r ollup.ques tionRespon seUpdates. formValida tionReport .formStatu sCollectio n.length;  x++){
  1137           if (rollup.qu estionResp onseUpdate s.formVali dationRepo rt.formSta tusCollect ion[x].sta tus != "CO MPLETE")
  1138                complete  = false;
  1139       }
  1140  
  1141       //if a  user is s ubmitting  an applica tion as an  expedited  study, th en they ne ed to meet  the three  requireme nts, which  the below  logic loo ks for
  1142       if(rol lupAnswers .contains( study.form .contained FormCollec tion[0].co ntainedFor m.formQues tionCollec tion[4].qu estion.ans werCollect ion[1].ans wersID)){
  1143           if (!(rollupA nswers.con tains(stud y.form.con tainedForm Collection [2].contai nedForm.fo rmQuestion Collection [1].questi on.answerC ollection[ 0].answers ID)))
  1144                expedite d_complete  = false;
  1145  
  1146           if (!(rollupA nswers.con tains(stud y.form.con tainedForm Collection [2].contai nedForm.fo rmQuestion Collection [1].questi on.answerC ollection[ 1].answers ID)))
  1147                expedite d_complete  = false;
  1148  
  1149           if (!(rollupA nswers.con tains(stud y.form.con tainedForm Collection [2].contai nedForm.fo rmQuestion Collection [1].questi on.answerC ollection[ 2].answers ID)))
  1150                expedite d_complete  = false;
  1151       }
  1152  
  1153       //fina lly, for a  user to s ubmit an a pplication , they hav e to eithe r be a PI  or CO-PI
  1154       if(com plete){
  1155           if (expedited _complete) {
  1156                if(study PI.contain sValue(cur rentUser.l oginName)) {
  1157                    //se tting up t he structu re for a u ser to sub mit their  applicatio n
  1158                    var  submitCont  = documen t.createEl ement("for m");
  1159                    subm itCont.set Attribute( "action",  "irb-appli cations.ht ml");
  1160  
  1161                    var  breaker =  document.c reateEleme nt("br");
  1162                    form ValidCont. appendChil d(breaker) ;
  1163  
  1164                    //in serting an  official  narrative  for users  to accept  while subm itting
  1165                    var  paragraph  = document .createEle ment("p");
  1166                    var  text = doc ument.crea teTextNode ("I accept  responsib ility for  assuring t hat this p rotocol wi ll be cond ucted in c ompliance  with ethic al clinica l practice s and all  applicable  VA, IRB,  FDA regula tions, IRB  and Insti tutional p olicies re lative to  the protec tion of th e rights,  welfare an d safety o f human su bjects.  I  acknowled ge that I  have the p rimary and  ultimate  responsibi lity for p rotecting  the rights  and welfa re of rese arch parti cipants an d that I u nderstand  the ethica l principl es of huma n subject  protection .  I affir m that I h ave the co mpetencies  and adequ ate resour ces and fa cilities t o carry ou t the prop osed resea rch and I  attest tha t this app lication i s scientif ically and  ethically  sound.  F inally, al l Conflict s of Inter ests have  been discl osed.");
  1167                    para graph.appe ndChild(te xt);
  1168                    subm itCont.app endChild(p aragraph);
  1169  
  1170                    var  paragraph  = document .createEle ment("p");
  1171                    var  text = doc ument.crea teTextNode ("In submi tting this  applicati on, I cert ify the ac knowledgem ents previ ously desc ribed and  that the r esearch te am is qual ified and  credential ed to cond uct this r esearch st udy.  I an d my study  team will  conduct a nd oversee  this proj ect in acc ordance wi th all eth ical stand ards requi red by the  VA for th e conduct  of human s ubjects re search.");
  1172                    para graph.appe ndChild(te xt);
  1173                    subm itCont.app endChild(p aragraph);
  1174  
  1175                    var  submission  = documen t.createEl ement("but ton");
  1176                    subm ission.set Attribute( "onclick",  "submitIR B()");
  1177                    var  text = doc ument.crea teTextNode ("Submit A pplication ");
  1178                    subm ission.app endChild(t ext);
  1179                    subm itCont.app endChild(s ubmission) ;
  1180  
  1181                    form ValidCont. appendChil d(submitCo nt);
  1182                }else{
  1183                    var  breaker =  document.c reateEleme nt("br");
  1184                    form ValidCont. appendChil d(breaker) ;
  1185  
  1186                    //no tifying us ers why th eir applic ation is i ncomplete
  1187                    var  paragraph  = document .createEle ment("p");
  1188                    var  text = doc ument.crea teTextNode ("You must  be either  the PI or  CO-PI to  submit an  applicatio n");
  1189                    para graph.appe ndChild(te xt);
  1190                    form ValidCont. appendChil d(paragrap h);
  1191                }
  1192           }e lse{
  1193                var brea ker = docu ment.creat eElement(" br");
  1194                formVali dCont.appe ndChild(br eaker);
  1195  
  1196                //notify ing users  why their  applicatio n is incom plete
  1197                var para graph = do cument.cre ateElement ("p");
  1198                var text  = documen t.createTe xtNode("Yo u have ide nitfied yo ur applica tion as be ing expedi ted, howev er you hav en't met a ll three e xpedited c agtegories  outlined  in Section  C");
  1199                paragrap h.appendCh ild(text);
  1200                formVali dCont.appe ndChild(pa ragraph);
  1201           }
  1202       }else{
  1203                var brea ker = docu ment.creat eElement(" br");
  1204                formVali dCont.appe ndChild(br eaker);
  1205  
  1206                //notify ing users  why their  applicatio n is incom plete
  1207                var para graph = do cument.cre ateElement ("p");
  1208                var text  = documen t.createTe xtNode("Yo u must com plete the  IRB applic ation befo re you can  submit.") ;
  1209                paragrap h.appendCh ild(text);
  1210                formVali dCont.appe ndChild(pa ragraph);
  1211        }
  1212  
  1213       return  formValid Cont;
  1214   };
  1215  
  1216   //changes  the status  of the ap plication  from "draf t" to "rev iew"
  1217   function s ubmitIRB() {
  1218       var de siredStage  = recentS tage + 1;
  1219       var us erID;
  1220  
  1221       for(va r i=0; i<u sers.user. length; i+ +){
  1222           if (users.use r[i].displ ayName ==  currentUse r.displayN ame)
  1223                userID =  users.use r[i].users ID;
  1224       }
  1225       sendRE ST("POST",  "manage/s tudy/"+ass ignedID+"/ stage/Revi ew?user="  + userID,  null, fals e);
  1226   };
  1227  
  1228   //opens a  new tab an d starts t he hipaa o r icf down load.
  1229   function g enerateHip aa(id){
  1230       var xm lhttp;
  1231  
  1232       if(id  == "13"){
  1233             window.ope n("http:// SERVER /sites/RAM S_UAT/Docu ments/Form %20Templat es/HIPAAFo rm.docx");
  1234       }else  if(id == " 12"){
  1235             window.ope n("http:// SERVER /sites/RAM S_UAT/Docu ments/Form %20Templat es/Consent Form.docx" );
  1236       }else  if(id == " 15"){
  1237           wi ndow.open( restPath.c oncat("stu dy/"+assig nedID+"/do cumentGene ration/1/1 3"));
  1238       }else  if(id == " 14"){
  1239           wi ndow.open( restPath.c oncat("stu dy/"+assig nedID+"/do cumentGene ration/1/1 4"));
  1240       }
  1241   };
  1242  
  1243   //puts tog ether the  content of  the popup  modal tha t allows u sers to se e what fil es
  1244   //they've  uploaded,  delete upl oaded file s, what qu estions th ey have le ft to answ er, allows  
  1245   //users to  generate  the hipaa  and consen t form, an d submit t he applica tion.
  1246   function r eviewApp() {
  1247       var re viewCont,  uploaded,  fileTable,  tableCont , fileHead , row, fil eBody;
  1248       
  1249       //remo ving any t race of a  previous p opup modal
  1250       $('#re view').rem ove();
  1251  
  1252       //putt ing togeth er the bas ic structu re and sty le of the  popup 
  1253       review Cont = doc ument.crea teElement( "div");
  1254       review Cont.setAt tribute("i d", "revie w");
  1255       review Cont.setAt tribute("c lass", "we ll");
  1256       review Cont.setAt tribute("s tyle", "ba ckground:  #fff");
  1257  
  1258       //gett ing all of  the files
  1259       upload ed = sendR EST("GET",  "fascade/ file/query study/" +  assignedID , null, fa lse);
  1260       
  1261       var te xt = docum ent.create TextNode(" Below are  all the fi les that y ou have up loaded:");
  1262       review Cont.appen dChild(tex t);
  1263       
  1264       tableC ont = docu ment.creat eElement(" div");
  1265       tableC ont.setAtt ribute("cl ass", "col -xs-12");
  1266  
  1267       fileTa ble = docu ment.creat eElement(" table");
  1268       fileTa ble.setAtt ribute("cl ass", "tab le table-b ordered ta ble-stripe d table-ho ver");
  1269  
  1270       fileHe ad = docum ent.create Element("t head");
  1271       
  1272       row =  document.c reateEleme nt("tr");
  1273       row.ap pendChild( createCell ("th", "Fi le", null) );
  1274       row.ap pendChild( createCell ("th", "Re move", nul l));
  1275  
  1276       fileHe ad.appendC hild(row);
  1277       fileTa ble.append Child(file Head);
  1278  
  1279       fileBo dy = docum ent.create Element("t body");
  1280       
  1281       //putt ing togeth er the tab le of file s
  1282       if((up loaded.fil es === und efined)||( uploaded.f iles.lengt h == 0)){
  1283           ro w = docume nt.createE lement("tr ");
  1284           ro w.appendCh ild((creat eCell("td" , "No File s Uploaded ", null))) ;
  1285           fi leBody.app endChild(r ow);
  1286           fi leTable.ap pendChild( fileBody);
  1287       }else{
  1288           fo r(var i=0;  i<uploade d.files.le ngth; i++) {
  1289                row = do cument.cre ateElement ("tr");
  1290                row.setA ttribute(" name", upl oaded.file s[i].file) ;
  1291                row.appe ndChild(cr eateCell(" td", uploa ded.files[ i].file, n ull));
  1292                row.appe ndChild(cr eateCell(" td", "dele te", uploa ded.files[ i].file, u ploaded.fi les[i].det ails[0].ta gs));
  1293                fileBody .appendChi ld(row);
  1294           }
  1295               fileTable .appendChi ld(fileBod y);
  1296       }
  1297       tableC ont.append Child(file Table);
  1298       review Cont.appen dChild(tab leCont);
  1299       
  1300       var te xt = docum ent.create TextNode(" Review you r applicat ion below: ");
  1301       review Cont.appen dChild(tex t);
  1302  
  1303       //vali date quest ions inser ts the res t of the r eviewing c ontent
  1304       review Cont.appen dChild(val idateQuest ions());
  1305  
  1306       var br eaker = do cument.cre ateElement ("br");
  1307       review Cont.appen dChild(bre aker);
  1308  
  1309       //butt on to clos e the wind ow
  1310       var cl oser = doc ument.crea teElement( "button");
  1311       closer .setAttrib ute("type" , "button" );
  1312       closer .setAttrib ute("oncli ck", "Func tion($('#r eview').po pup('toggl e'))");
  1313  
  1314       var te xt = docum ent.create TextNode(" Close Wind ow");
  1315       closer .appendChi ld(text);
  1316  
  1317       review Cont.appen dChild(clo ser);
  1318  
  1319       //spec ific libra ry code to  show popu p
  1320       $('bod y').append (reviewCon t);
  1321       $('#re view').pop up('show') ;
  1322   };
  1323  
  1324   //creates  a cell in  a table. t ype is wha t kind of  cell to cr eate,
  1325   //content  is what go es in the  cell, tag  is used to  pass file
  1326   //informat ion (since  the only  table is u sed with f iles)
  1327   function c reateCell( type, cont ent, tag,  id){
  1328       
  1329       var ce ll = docum ent.create Element(ty pe);
  1330       
  1331       var te xt = docum ent.create TextNode(c ontent);
  1332       
  1333       if(con tent == "d elete"){
  1334           // styling de lete text
  1335           va r anchor =  document. createElem ent("a");
  1336           an chor.style .color = " blue";
  1337           an chor.style .textDecor ation = "u nderline";
  1338           an chor.style .textDecor ationColor  = "blue";
  1339           an chor.style .cursor =  "pointer";
  1340           
  1341           an chor.appen dChild(tex t);
  1342           ce ll.appendC hild(ancho r);
  1343  
  1344           // tag here i s used to  link the r emove butt on to a sp ecific fil e
  1345           ce ll.setAttr ibute("onc lick", "re moveFile(' "+tag+"',  "+id+")");
  1346       }else  if(content  == "No Fi les Upload ed"){
  1347           ce ll.appendC hild(text) ;
  1348           ce ll.setAttr ibute("col span", "2" );
  1349       }else{
  1350           ce ll.appendC hild(text) ;
  1351       }
  1352       
  1353       return  cell;
  1354   };
  1355  
  1356   //rest cal l for remo ving a fil e from the  cache and  from
  1357   //the tabl e
  1358   function r emoveFile( file, id){
  1359       var st atus;
  1360       var qR esponse =  {};
  1361       var da ta = [];
  1362       var re sponse = { };
  1363  
  1364       status  = sendRES T("DELETE" , "fascade /file/dele te/study/" +assignedI D+"/filena me/"+file,  null, fal se);
  1365       $('[na me="'+file +'"]').rem ove();
  1366  
  1367       respon se = {
  1368           "q uestionsID ": id
  1369       };
  1370  
  1371       data.p ush(respon se);
  1372  
  1373       //prop erly packa ging to se nd through  REST call
  1374       qRespo nse = {
  1375       "quest ionRespons e": data
  1376       };
  1377  
  1378       sendRE ST("POST",  "study/"+ assignedID +"/respons es/"+recen tStage, qR esponse, f alse);
  1379  
  1380   };
  1381  
  1382   //assignin g the appr opriate ic ons to the  buttons i n the side bar
  1383   function u pdateSideb arIcons(ta rgetSectio n){
  1384       //grab bing all o f the sect ion button s
  1385       var si deButtons  = $('.list -group-ite m');
  1386       var in complete=0 ;
  1387       var co mplete=0;
  1388       var em pty=0;
  1389       var to tal;
  1390       
  1391       //remo ving previ ous icons
  1392       $('.gl yphicon-ad just').rem ove();
  1393       $('.gl yphicon-re cord').rem ove();
  1394       $('.gl yphicon-ok -circle'). remove();
  1395       
  1396       getRol lup();
  1397  
  1398       //goin g through  the most r ecent user 's respons es and ass igning the m the corr ect icons  as
  1399       //well  as giving  the relev ant button s a link.
  1400       for(va r i=0; i<s ideButtons .length-2;  i++){
  1401           if (assignedI D == "1"){
  1402                if(i ==  0){
  1403                    var  icon = doc ument.crea teElement( "span");
  1404                    icon .setAttrib ute("class ", "glyphi con glyphi con-record ");
  1405                    side Buttons[i] .appendChi ld(icon);
  1406                }
  1407  
  1408                sideButt ons[i].set Attribute( "onclick",  "insertWa rning('You  must comp lete Secti on A and S ave your r esponses b efore proc eeding.',  'alert-war ning')");
  1409           }e lse{
  1410                var icon  = documen t.createEl ement("spa n");
  1411                if(rollu p.question ResponseUp dates.form Validation Report.for mStatusCol lection[i] .status ==  "INCOMPLE TE"){
  1412                             icon.s etAttribut e("class",  "glyphico n glyphico n-adjust") ;
  1413                             incomp lete += 1;
  1414                             sideBu ttons[i].s etAttribut e("onclick ", "checkS ave("+i+") ");
  1415                    side Buttons[i] .setAttrib ute("style ", "cursor : pointer" );
  1416                }else if (rollup.qu estionResp onseUpdate s.formVali dationRepo rt.formSta tusCollect ion[i].sta tus == "NO T_APPLICAB LE"){
  1417                    //wh en a secti on isn't r equired a  user shoul dn't be ab le to clic k on it an d
  1418                    //it  shouldn't  have an i con
  1419                    side Buttons[i] .removeAtt ribute("on click");
  1420                    side Buttons[i] .setAttrib ute("style ", "cursor : not-allo wed");
  1421                }else if (rollup.qu estionResp onseUpdate s.formVali dationRepo rt.formSta tusCollect ion[i].sta tus == "EM PTY"){
  1422                    icon .setAttrib ute("class ", "glyphi con glyphi con-record ");
  1423                    side Buttons[i] .setAttrib ute("oncli ck", "chec kSave("+i+ ")");
  1424                    side Buttons[i] .setAttrib ute("style ", "cursor : pointer" );
  1425                    empt y += 1;
  1426                }else if (rollup.qu estionResp onseUpdate s.formVali dationRepo rt.formSta tusCollect ion[i].sta tus == "CO MPLETE"){
  1427                             icon.s etAttribut e("class",  "glyphico n glyphico n-ok-circl e");
  1428                             sideBu ttons[i].s etAttribut e("onclick ", "checkS ave("+i+") ");
  1429                    side Buttons[i] .setAttrib ute("style ", "cursor : pointer" );
  1430                             comple te += 1;
  1431                }
  1432                sideButt ons[i].app endChild(i con);
  1433           }
  1434       }
  1435       //upda tes the ge neral info rmation se ction that  gives the  user
  1436       //a qu ick glance  of how mu ch they ha ve left to  do
  1437       total  = incomple te+empty+c omplete;
  1438       $('.se ctionLocat ion').html ("Complete d: " + com plete + "/ " + total) ;
  1439   };
  1440  
  1441   function c reateStudy (){
  1442       var fa cilities,  users, id,  titleID,  packaging;
  1443       var us erTable =  new Hashta ble();
  1444  
  1445       //grab s a new ge nerated st udy id
  1446       var te mp = sendR EST("GET",  "fascade/ studyidgen erator/sit ecode/1111 /humorani/ H", null,  false); 
  1447       assign edID = tem p.studyAss ignedID;
  1448  
  1449       //grab s all the  studies th at have be en created .
  1450       studie s = sendRE ST("GET",  "manage/st udy", null , false);
  1451  
  1452       //form atting the  recieved  JSON
  1453       if((st udies.stud y.length = == undefin ed) || (st udies.stud y.length = = 0)){
  1454           st udyID = 1;
  1455       }else{
  1456          var  studyLeng th = studi es.study.l ength - 1;
  1457           st udyID = st udies.stud y[studyLen gth].studi esID + 1;
  1458       }
  1459  
  1460       //grab bing all t he users i n the data base and f ormatting  the reciev ed JSON
  1461       users  = sendREST ("GET", "u ser", null , false);
  1462       if(use rs.user.le ngth === u ndefined)
  1463           us ers.user =  [users.us er];
  1464  
  1465       //chec king to se e if the u ser is in  the sql da tabase
  1466       for(va r i=0; i<u sers.user. length; i+ +){
  1467           us erTable.pu t(users.us er[i].disp layName, u sers.user[ i].usersID );
  1468       }
  1469  
  1470       //a ne w study ha s to be li nked to a  facility
  1471       facili ties = sen dREST("GET ", "facili ty", null,  false);
  1472       if(fac ilities.fa cility.len gth === un defined)
  1473           fa cilities.f acility =  [facilitie s.facility ];
  1474               
  1475       if(fac ilities.fa cility.len gth == 0){
  1476           // inserting  a facility  if the da tabase doe sn't hold  any
  1477           
  1478           va r addFacil ity = {
  1479                "adminis tratorSPGr oup": 0,
  1480                "descrip tion": "in itial faci lity",
  1481                "facilit iesID": 0,
  1482                "name":  "General S ite",
  1483                "reviewe rSPCalenda r": "00000 000-0000-0 000-0000-0 0000000000 0",
  1484                "reviewe rSPGroup":  0,
  1485                "safetyS PGroup": 0
  1486           };
  1487           
  1488           fa cility = {
  1489                "facilit y": addFac ility
  1490           };
  1491           
  1492           se ndREST("PO ST", "mana ge/facilit y", facili ty, false) ;
  1493       }
  1494       
  1495       //pack aging stud y
  1496       facili ty = {
  1497           "f acilitiesI D": facili ties.facil ity[0].fac ilitiesID
  1498       };
  1499  
  1500       //we k now we are  only crea ting the s tudy when  we are on  the first  page, grab bing the s tudy title
  1501       titleI D = study. form.conta inedFormCo llection[0 ].containe dForm.form QuestionCo llection[0 ].question .questions ID;
  1502       studyT itle = $(" [name = 'Q ID_"+title ID+"']").v al();
  1503  
  1504       packag ing = {
  1505           "a ssignedID" : assigned ID,
  1506           "f acility":  facility,
  1507           "s tudiesID":  studyID,
  1508           "t itle": stu dyTitle
  1509       };
  1510  
  1511       var da ta = {
  1512           "s tudy": pac kaging
  1513       };
  1514  
  1515       //putt ing the ne wly create d study in  the datab ase
  1516       sendRE ST("POST",  "manage/s tudy?user= " + userTa ble.get(cu rrentUser. displayNam e), data,  false);
  1517   };
  1518  
  1519  
  1520   function i nitialSect ionCheck() {
  1521       var se ction, req uired;
  1522       var qu estionColl ection = n ew HashSet ();
  1523  
  1524       sectio n = study. form.conta inedFormCo llection[0 ].containe dForm.form QuestionCo llection; 
  1525  
  1526       for(va r i=0; i<s ection.len gth; i++){
  1527           re quired = t rue;
  1528  
  1529           // grabbing a  specific  question
  1530           qu estion = s ection[i]. question.q uestionsID ;
  1531  
  1532           if (section[i ].required Predecesso rAnswersID ){
  1533                //here w e are look ing into f irst level  dependent  questions . With the  current 
  1534                //sectio n A, there  isn't a q uestion de pendency w here quest ion C depe nds on que stion
  1535                //B whic h depends  on questio n A (secon d level de pendency);
  1536                var pare nt = secti on[i].requ iredPredec essorAnswe rsID; 
  1537  
  1538                if(!($(" #"+parent) .is(':chec ked'))){
  1539                    requ ired = fal se; 
  1540                }
  1541           }
  1542  
  1543           if (required) {
  1544                if((sect ion[i].que stion.resp onseFormat .name == " radio") ||  (section[ i].questio n.response Format.nam e == "chec kbox")){
  1545                    var  complete =  false;
  1546                    var  answers =  $('[name=" QID_'+ques tion+'"]') ;
  1547  
  1548                    for( var j=0; j <answers.l ength; j++ ){
  1549                         var id = a nswers[j]. getAttribu te("id");
  1550  
  1551                         if($("#"+i d).is(':ch ecked')){
  1552                             comple te = true;
  1553                         }
  1554                    }
  1555  
  1556                    if(c omplete !=  true){
  1557                         return fal se;
  1558                    }
  1559  
  1560                }else if (section[i ].question .responseF ormat.name  == "selec t"){
  1561                    if($ ("[name =  '"+questio n+"']").fi nd(':selec ted').val( ) == "none "){
  1562                         return fal se;
  1563                    }
  1564  
  1565                }else{
  1566                    if($ ("[name =  '"+questio n+"']").va l() == "") {
  1567                         return fal se;
  1568                    }
  1569                }
  1570           }
  1571       }
  1572       return  true;
  1573   }
  1574  
  1575   //grabbing  all user  input and  packaging  it up to s end to the  database
  1576   function c reateRespo nses(){
  1577       var ch angedPacka ge; 
  1578       var qR esponse =  {};
  1579       var da ta = [];
  1580       var re sponse = { };
  1581       var qu estion, up loaders; 
  1582  
  1583       if(ass ignedID ==  "1"){
  1584           if (!initialS ectionChec k()){
  1585                insertWa rning('You  must comp lete Secti on A and s ave your r esponses b efore proc eeding.',  'alert-war ning');
  1586  
  1587                return;
  1588           }e lse{
  1589  
  1590                createSt udy();
  1591  
  1592                //Gettin g the most  recent st age to use  later
  1593                studyRes ponse = se ndREST("GE T", "study /"+assigne dID, null,  false);
  1594                if(!("le ngth" in s tudyRespon se.study.s tudyStatus Collection ))
  1595                    stud yResponse. study.stud yStatusCol lection =  [studyResp onse.study .studyStat usCollecti on];
  1596                recentSt age = stud yResponse. study.stud yStatusCol lection.le ngth;
  1597  
  1598                $('div.p age-header ').empty() ;
  1599                headerBu ilder(0);                           
  1600           }
  1601       }
  1602  
  1603       //look ing for up loaded fil es to send  to the ca che
  1604       upload ers = $('[ type="file "]');
  1605       for(va r i=0; i<u ploaders.l ength; i++ ){
  1606           if (uploaders [i].value) {
  1607                var file  = uploade rs[i].valu e.split("\ \");
  1608  
  1609                //packag ing up the  file info rmation an d storing  it in the  cache
  1610                var requ est = new  XMLHttpReq uest();
  1611                request. open("POST ", restPat h.concat(" fascade/fi le/upload/ onlyfilena me"), fals e);
  1612                request. setRequest Header("fi lename", f ile[file.l ength-1]);
  1613                request. setRequest Header("lo gin_name",  currentUs er.display Name);
  1614                request. setRequest Header("st udy_id", a ssignedID) ;
  1615                request. setRequest Header("ta gs", (uplo aders[i].n ame).repla ce('QID_',  ''));
  1616                request. send(null) ;
  1617  
  1618                response  = {
  1619                    "que stionsID":  (uploader s[i].name) .replace(' QID_', '') ,
  1620                    "res ponse": fi le[file.le ngth-1]
  1621                };
  1622                data.pus h(response );
  1623  
  1624                insertWa rning('You  have succ essfully s aved your  responses' , 'alert-s uccess');
  1625                if(chang edQuestion s.contains (parseInt( (uploaders [i].name). replace('Q ID_', '')) )){
  1626                    chan gedQuestio ns.remove( parseInt(( uploaders[ i].name).r eplace('QI D_', ''))) ;
  1627                }
  1628           }
  1629       }
  1630  
  1631       if((st udyTitleID  != "0") & & (changed Questions. contains(s tudyTitleI D))){
  1632  
  1633           st udyTitle =  $('[name= "QID_'+stu dyTitleID+ '"]').val( );
  1634  
  1635           // packaging  up the fil e informat ion and st oring it i n the cach e
  1636           va r request  = new XMLH ttpRequest ();
  1637           re quest.open ("POST", r estPath.co ncat("stud y/"+assign edID+"/new Title"), t rue);
  1638           re quest.setR equestHead er("newTit le", study Title);
  1639           re quest.send (null);
  1640  
  1641           $( 'div.page- header').e mpty();
  1642           he aderBuilde r(0);
  1643       }
  1644  
  1645       //chan ged questi ons keeps  track of w hat questi ons the us er
  1646       //has  modified w hile filli ng out the  current s ection. we  only
  1647       //want  to packag e up and s end these  questions
  1648       change dPackage =  changedQu estions.va lues();
  1649       change dQuestions  = new Has hSet();
  1650       
  1651       //Filt ering thro ugh each c hanged que stion and  packaging  it up base d on what
  1652       //type  of input  it is.
  1653       for(va r i=0; i<c hangedPack age.length ; i++){
  1654           va r toPackag e = $('[na me="QID_'+ changedPac kage[i]+'" ], #AID_'+ changedPac kage[i]+'' );
  1655           fo r(var j=0;  j<toPacka ge.length;  j++){
  1656                if((toPa ckage[j].t ype == "ra dio")) {
  1657                         //have to  grab the s et of radi os assigne d to a que stions and  see 
  1658                         //which on e is actua lly select ed to send  to the da tabase
  1659                    if(t oPackage[j ].checked  == true){
  1660                         response =  {
  1661                         "answersID ": (toPack age[j].id) .replace(' AID_', '') ,
  1662                         "questions ID": (toPa ckage[j].n ame).repla ce('QID_',  '')
  1663                         };
  1664                         data.push( response);
  1665                    }
  1666                }else if ((toPackag e[j].type  == "checkb ox")){
  1667                    //th ere's a di fference i n how chec ked checkb oxes
  1668                    //ar e sent vs  how unchec ked checkb oxes are s ent
  1669                    if(t oPackage[j ].checked  == true){
  1670                         response =  {
  1671                             "answe rsID": (to Package[j] .id).repla ce('AID_',  ''),
  1672                             "check boxIndex":  toPackage [j].title,
  1673                             "quest ionsID": ( toPackage[ j].name).r eplace('QI D_', '')
  1674                         };
  1675                    data .push(resp onse);
  1676                    }els e if(toPac kage[j].ch ecked == f alse){
  1677                         response =  {
  1678                             "check boxIndex":  toPackage [j].title,
  1679                             "quest ionsID": ( toPackage[ j].name).r eplace('QI D_', '')
  1680                         };
  1681                    data .push(resp onse);
  1682                    }
  1683                }else if ((toPackag e[j].type  == "text")  || (toPac kage[j].ty pe == "tex tarea") ||  (toPackag e[j].type  == "select -one")){
  1684                         //everythi ng else is  pretty st raightforw ard to sen d
  1685                         response =  {
  1686                         "questions ID": (toPa ckage[j].n ame).repla ce('QID_',  ''),
  1687                         "response" : toPackag e[j].value
  1688                         };
  1689                    data .push(resp onse);
  1690                }
  1691           } 
  1692       }
  1693       
  1694  
  1695       //prop erly packa ging to se nd through  REST call
  1696       qRespo nse = {
  1697           "q uestionRes ponse": da ta
  1698       };
  1699  
  1700  
  1701       //only  making a  xmlhttp re quest if u ser has up dated ques tions
  1702       if(dat a[0] != nu ll)
  1703           se ndREST("PO ST", "stud y/"+assign edID+"/res ponses/"+r ecentStage , qRespons e, false);
  1704  
  1705       rollup Answers =  new HashSe t();
  1706  
  1707       //gett ing curren t target s ection to  pass 
  1708       if(dat a[0] != nu ll){
  1709           va r sidebar  = $('.list -group-ite m');
  1710           va r current  = $('.list -group-ite m.active') ;
  1711           fo r(var i=0;  i<sidebar .length-2;  i++){
  1712                if(sideb ar.get(i)  == current .get(0)){
  1713                    //up dating sid ebar icons  now that  we have th e section  that
  1714                    //sh ould show  up as acti vated.
  1715                    upda teSidebarI cons(i);
  1716  
  1717                    //al erting use rs of exem pt questio n constrai nts
  1718                    if(i  == 2){
  1719                         //if a use r is submi tting an a pplication  as an exp edited stu dy, then t hey need t o meet the  three req uirements,  which the  below log ic looks f or
  1720                         if(rollupA nswers.con tains(stud y.form.con tainedForm Collection [0].contai nedForm.fo rmQuestion Collection [4].questi on.answerC ollection[ 1].answers ID)){
  1721                             if(!(r ollupAnswe rs.contain s(study.fo rm.contain edFormColl ection[2]. containedF orm.formQu estionColl ection[1]. question.a nswerColle ction[0].a nswersID)) ){
  1722                                 in sertWarnin g("You hav e selected  that your  applicati on is expe dited, but  you haven 't checked  all three  expedited  categorie s", "alert -warning") ;
  1723                             }else  if(!(rollu pAnswers.c ontains(st udy.form.c ontainedFo rmCollecti on[2].cont ainedForm. formQuesti onCollecti on[1].ques tion.answe rCollectio n[1].answe rsID))){
  1724                                 in sertWarnin g("You hav e selected  that your  applicati on is expe dited, but  you haven 't checked  all three  expedited  categorie s", "alert -warning") ;
  1725                             }else  if(!(rollu pAnswers.c ontains(st udy.form.c ontainedFo rmCollecti on[2].cont ainedForm. formQuesti onCollecti on[1].ques tion.answe rCollectio n[2].answe rsID))){
  1726                                 in sertWarnin g("You hav e selected  that your  applicati on is expe dited, but  you haven 't checked  all three  expedited  categorie s", "alert -warning") ;
  1727                             }
  1728                         }
  1729                    }
  1730                }
  1731           }
  1732       }
  1733   };