///////////////////////////////////////////////////////////////////////////
// Making changes to the JavaScript below violates your CfMC support
// agreement.  DO NOT MAKE CHANGES TO THIS SCRIPT!
///////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// initial80.js - javascript for index.html
//   written by   - ??????? cbova/cmckinney
//   last updated - 27jul06 - added new functions for submit, onload
//
//
////////////////////////////////////////////////////////////
// Controls popup window that survey runs in.
// Handles filling out of form from hotlinks
//   http://server.where.com/dir/index.html?name=ABC&password=XYZ
//   http://server.where.com/dir/index.html?ID=ABC123
// Also can remember name and password in a cookie
//
// Variables set externally are:
//   use_popwindows = true/false;
//   xsize = pixels; // size of the pop-up window
//   ysize = pixels;
//   xcorner = pixels; // position of the pop-up window
//   ycorner = pixels;
//   use_autostart = true/false; // submit index page if name/passwd are known
//   use_cookies = true/false;
//   cookie_lifetime = days;     // how many day till cookie expires
////////////////////////////////////////////////////////////
// all the controling variables
////////////////////////////////////////////////////////////
var use_cookies
var use_popwindows;
var use_autostart;
var has_priority;
var cookie_lifetime;
var login_from;
var query_built;
var name_in_link = "name";
var password_in_link = "password";
var default_name = "respondent"
var id_in_link = "id";
var submit_ok = true;

////////////////////////////////////////////////////////////
var undefined;
var oreos = false, where = "!!!";
var popup = false;
var start = false;
var first = "cookies";
var life  = 30;
var FORM;
var popit;
var have_cookie = false;

//alert(document.forms["cfmclogin"].elements["NAME"] + " " + document.forms["cfmclogin"].elements["PASSWORD"]);

//used for adding mutliple onload, onsubmit functions
var MyLoadArray = new Array();
var MySubmitArray = new Array();

if (document.forms["cfmclogin"] != undefined) {
   FORM = document.cfmclogin;
}

////////////////////////////////////////////////////////////
// the heart of the matter
//  0) inititalize all my local variables
//  1) try to fill out form automatically
//  2) if form filled out, maybe pop open a window, set a cookie and start
//  3) else, maybe pop open a window and set a cookie, when start is clicked
////////////////////////////////////////////////////////////
function runit () {
   var ok = false;

   if (use_autostart == undefined) use_autostart  = false;
   if (use_popwindows == undefined) use_popwindows = true;
   if (use_cookies == undefined) use_cookies    = false;
   if (login_from == undefined) login_from = "link";
   if (cookie_lifetime != undefined) cookie_lifetime = life;

   start = use_autostart;
   popup = use_popwindows;
   oreos = use_cookies;

   var login = login_from.split(":");

   for (var i=0 ; i < login.length ; ++i) {
      if (login[i] == "link") {
         ok = login_link();
         //alert("Login using Link: " + ok);
         if (ok) break;
      }
      if (login[i] == "cookie" && oreos) {
         ok = login_cookie();
         //alert("Login using Cookie: " + ok);
         if (ok) have_cookie = true;
         if (ok) break;
      }
      if (login[i] == "random") {
         ok = login_random();
         //alert("Login using Random: " + ok);
         if (ok) break;
      }
   }

   if (ok && start) {
      if (oreos && !have_cookie) set_cfmc_cookie(life);
      pass_query();

      if (popup) popit = popopen();

      if (popit != undefined) {
        setTimeout("popit.focus()", 500);
      }

      FORM.submit();
   }
}

////////////////////////////////////////////////////////////
// fill out name/password from the url?query
//   query = (name=xxx&password=yyy) or (id=abc)
////////////////////////////////////////////////////////////
function login_link () {

   var w = window;
   if (window.parent != undefined) w = window.parent;

   var query  = w.location.search.substring(1) + "&";

   if (window.navigator.userAgent.toLowerCase().match("gecko")) {navigator.family = "gecko"}

   // ### retains spaces in URL.  Other wise they come thorugh as "%20"
   if (navigator.family == "gecko") {
      var old = false;
   } else {
      var old = true;
   }

   if (old) {query = unescape(query);}
   if (!old) {query = decodeURI(query);}

   var name   = getvalue(query, name_in_link);
   var passwd = getvalue(query, password_in_link);
   var id     = getvalue(query, id_in_link);

   var CATI = false;
   var Booth;
   var Practice_Mode;
   var Special_Types;
   var EXTN;
   var TZone;
   var SoundChannel;


   for (var a = 0; a < document.forms[0].length; a++) {
      
      
         ThisElement = document.forms[0].elements[a];
         if (ThisElement.name == "USE_PASSWDS") {
             CATI = ThisElement;
             continue;
         }    
         
         if (ThisElement.name == "booth") {
             Booth = ThisElement;
             continue;
         }    
             
         if (ThisElement.name == "practice_mode") {
             Practice_Mode = ThisElement;
             continue;
         }    

         if (ThisElement.name == "special_types") {
             Special_Types = ThisElement;
             continue;
         }    

         if (ThisElement.name == "extn") {
             EXTN = ThisElement;
             continue;
         }    

         if (ThisElement.name == "timezone") {
             TZone = ThisElement;
             continue;
         }    

         if (ThisElement.name == "soundchannel") {
             SoundChannel = ThisElement;
             continue;
         }    
   }


   if (CATI.value == "CATI") {
   
      var Booth_Link   = getvalue(query, "booth");
      var Practice_Link = getvalue(query,"practice_mode");
      var Special_Link = getvalue(query,"special_types");
      var EXTN_Link = getvalue(query, "extn");
      var TZone_Link = getvalue(query, "timezone");     
      var Sound_Link = getvalue(query, "soundchannel");

     
      if (Booth_Link.length > 0) Booth.value = Booth_Link;
      if (Special_Link.length > 0) Special_Types.value = Special_Link;
      if (EXTN_Link.length > 0) EXTN.value = EXTN_Link;
      
      if (TZone_Link.length > 0 && TZone != undefined)  TZone.value = TZone_Link;;  
      if (Sound_Link.length > 0 && SoundChannel != undefined)  SoundChannel.value = Sound_Link;;        
            
      if (Practice_Mode != undefined) {
        if (Practice_Link == "1") {
            Practice_Mode.checked = true;
        } else {
            Practice_Mode.checked = false;
        }
      }  
    }    
  
   if (id.length > 0) {
      name = default_name;
      passwd = id;
   }

   if (name.length == 0 && passwd.length == 0 && CATI === false) return false;

   fillout_form(name, passwd);

   MakeReadOnly();
   
   return true;
}


////////////////////////////////////////////////////////////
// fill out the login form from a cookie
////////////////////////////////////////////////////////////
function login_cookie() {
   var study = find_element("studycode");
   var cookie_pass = find_element("cookie_pass");
   var oreo = get_cookie(study.value);

   if (oreo[0] == "!!!") return false;

   if (cookie_pass == undefined  || oreo[3] == "!!!" || (cookie_pass != undefined && cookie_pass.value != oreo[3])) {
      if (oreo[0] != study.value) return false;
   }
   
   //if (oreo[1] == "!!!" && oreo[2] == "!!!") return false;

   fillout_form(oreo[1], oreo[2]);

   MakeReadOnly();

   return true;
}

////////////////////////////////////////////////////////////
// fill out the login form using random name/password
////////////////////////////////////////////////////////////
function login_random() {
   var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

   if (FORM.password != null) var r_pass = FORM.password;
   if (FORM.PASSWORD != null) var r_pass = FORM.PASSWORD;

   if (FORM.name != null) var r_name = FORM.name;
   if (FORM.NAME != null) var r_name = FORM.NAME;

   if (r_pass == null || r_name == null) return false;

   if (r_pass.value.length < 1) {
    var pass = random_word(characters, 8);
   }  else {
    var pass = r_pass.value;
   }

   if (r_name.value.length < 1) {
    var name = random_word(characters, 10);
   } else {
    var name = r_name.value;
   }

   fillout_form(name, pass);
   return true;
}

////////////////////////////////////////////////////////////
// open a new window that becomes the FORM's target
////////////////////////////////////////////////////////////
var xsize, ysize, xcorner, ycorner;
function popopen() {
   var undefined;

   var XD = 700;   if (xsize   != undefined) XD = xsize;
   var YD = 400;   if (ysize   != undefined) YD = ysize;
   var XP =  30;   if (xcorner != undefined) XP = xcorner;
   var YP = 100;   if (ycorner != undefined) YP = ycorner;

   var pars = "resizable=1,scrollbars=1,status=1";
   var size = "width=" + XD + ",height=" + YD;
   var loca = "left=" + XP + ",top=" + YP;
   pars += "," + size + "," + loca;

   var popname = "cfmcpopup";
   var study = find_element("studycode");
   if (study != undefined) popname = "cfmc" + study.value;

   var pop = open("",popname,pars);
   FORM.target = popname;
   if (pop != null) pop.focus();

   return pop;
}

////////////////////////////////////////////////////////////
// set a cookie
//   the cookie is "cfmc[studycode]=name+password"
////////////////////////////////////////////////////////////
function set_cookie (ndays) {
   var cookie;
   if (!oreos) return;

// cookie expiration
   var today = new Date();
//   alert("life = " +  ndays);
   var expry = Date.parse(today) + (24*60*60*1000) * ndays;
   expry = new Date(expry);
   expry = expry.toGMTString();

// the cookie is "cfmc[studycode]=name+password"
   var study  = find_element("studycode");
   var name   = find_element("name");
   var passwd = find_element("password");
   var cookie_pass = find_element("cookie_pass");

   if (study == undefined || name == undefined || passwd == undefined) return;

   cookie  = "cfmc" + study.value + "=";
   cookie += escape( name.value ) + "+" + escape( passwd.value );
   if (cookie_pass != undefined) {
    cookie += "+" +  escape( cookie_pass.value);
   }
   cookie += ";expires=" + expry;
   cookie += "; path=/; domain=" + document.location.hostname;

//   alert("wow");
//   alert(cookie);

//   alert("Set Cookie: " + "study = " + study.value  + "\n" +
//                      "name  = " + name.value   + "\n" +
//                      "pass  = " + passwd.value + "\n" +
//                      "expry = " + expry        + "\n");

   document.cookie = cookie;

}

////////////////////////////////////////////////////////////
// get a cookie
////////////////////////////////////////////////////////////
function get_cookie (study) {
   var undefined;
   var cookie = new Array("!!!", "!!!", "!!!", "!!!");
   var today = new Date();
   var found = false;
   var cookie_pass = find_element("cookie_pass");

//   alert(document.cookie.length);
   if (study == undefined) {
//      alert(study);
      return cookie;
   }
   if (document.cookie.length == 0) {
//      alert(document.cookie.length);
      return cookie;
   }


   // actually see a string of all cookies available
   var all_cookies = document.cookie.split(";");

   var c = new Array();
   for (var k=0 ; k < all_cookies.length ; k++) {
      c = all_cookies[k].split("=");
      while (c[0].substr(0, 1) == " ") { c[0] = c[0].substr(1); }
      c[0] = c[0].substr(4);

       if (c[0] == study || cookie_pass != undefined) {
         var tmp = c[1].split("+");
         //c[3] = new Date(c[2]);
         c[1] = unescape(tmp[0]);
         c[2] = unescape(tmp[1]);
         c[3] = unescape(tmp[2]);
         found = true;
         break;
      }
   }

//   alert(found);

   if (! found) return cookie;
   //alert("GetCookie(" + study + "): " + "\n" +
   //                  "study = " + c[0] + "\n" +
   //                  "name  = " + c[1] + "\n" +
   //                  "pass  = " + c[2] + "\n" +
   //                  "expry = " + c[3] + "\n");

   //if (c[3].valueOf() <= today.valueOf()) return cookie; // expired

   cookie[0] = c[0];
   cookie[1] = c[1];
   cookie[2] = c[2];
   cookie[3] = c[3];

   return cookie;

}

////////////////////////////////////////////////////////////
// set up the cookie manager so it runs
////////////////////////////////////////////////////////////
function cookie_manager () {
   CM = document.forms.CookieMgr;

   CM.clearcookie.onclick = function () {
      var study  = find_element("studycode");
      var name   = find_element("name ");
      var passwd = find_element("password");

      study  = (study  != undefined) ? study.value  : "!!!";
      name   = (name   != undefined) ? name.value   : "!!!";
      passwd = (passwd != undefined) ? passwd.value : "!!!";

      set_cookie(-30);
      fillout_form("", "");
   }

   CM.showcookie.onclick = function () {
      var study = find_element("studycode").value;
      //study = study.substr(0,3);  // this line added for ISA
      var oreo = get_cookie(study);

      var msg = "All cookies =*" + document.cookie + "*\n";

      msg += "\nCookie: study    = " + oreo[0];
      msg += "\n        name     = " + oreo[1];
      msg += "\n        password = " + oreo[2];
//      alert(msg);
   }

}

////////////////////////////////////////////////////////////
// pick off value part of a name=value& pair
////////////////////////////////////////////////////////////
function getvalue (string, name) {
   var arr = string.split("&");
   var blank = "";
   var name = name.toUpperCase();

   for (var i = 0 ; i < arr.length ; i++) {
      var pair = arr[i].split("=");
      var pname = pair[0].toUpperCase();
      if (name == pname) return pair[1];
   }
   return blank;
}

////////////////////////////////////////////////////////////
// find an element in the cfmclogin form
////////////////////////////////////////////////////////////
function find_element (name) {
   var ucname = name.toLowerCase();
   var undefined;
   for (var i = 0 ; i < FORM.length ; i++) {

      if (FORM.elements[i].name == undefined) continue;

      var el_name = FORM.elements[i].name.toLowerCase();
      if (el_name == ucname) return FORM.elements[i];
   }
   return undefined;
}

////////////////////////////////////////////////////////////
// fill out the form
////////////////////////////////////////////////////////////
function fillout_form (name, passwd) {
   var N = find_element("name");
   var P = find_element("password");
   
   //alert(N.value + " and " + name);
   if (N != undefined && name != undefined && name != "") N.value = name;
   if (P != undefined && passwd != undefined) P.value = passwd;
}

function random_word (charset, len) {
   var setlen = charset.length;
   var word = "";
   for (var i=0 ; i < len ; ++i) {
      var k = Math.floor(Math.random() * setlen);
      word += charset.substr(k, 1);
   }
   return word;
}

function pass_query() {
      if (query_built == true) return;
      var win = window;
      if (window.parent != undefined) win = window.parent;

            if (navigator.family == "gecko") {
              var old = false;
            } else {
              var old = true;
            }

        // ### retains spaces in URL.  Other wise they come thorugh as "%20"


            var query  = win.location.search.substring(1);

            if (old) {query = unescape(query);}
            if (!old) {query = decodeURI(query);}

            if (query.length > 0) {
             document.cfmclogin.action += "?" + query;
             query_built = true;
            }
}


//********************SetStyle function **************************************************

//  Purpose:  Use to change the specific style of an object.  Can change more than one style element
//            element id, style property name:style property value
//            if sending more than on property name/value separate with a comma
//
//  Date:     09/06/06
//  Changes:

//************************************************************************************************

function SetStyle(element,prop1,prop2) {

   var this_object;
   var undefined;

   //netscape 4.7? and below are disallowed
   if (document.layers) {
     return false;
   }

   //detect browser set variable to find id of object if it exists

   if (document.all && document.all["" + element + ""] != null)  this_object = document.all["" + element + ""];
   if (document.getElementById && document.getElementById("" + element + "") != null) this_object = document.getElementById("" + element + "");

   if (this_object == undefined) {
     alert("PROGRAMMER ALERT:  Something is wrong.  Either the browser detection failed or the id you passed was invalid");
     return false;
   }

   for (var a = 1; a < SetStyle.arguments.length;a++) {

       prop = SetStyle.arguments[a].split(":");
       this_prop_name = prop[0];
       this_prop_value = prop[1];

       try {
        this_object.style[""+this_prop_name+""] = this_prop_value;
       }
       catch(e) {
        alert("PROGRAMMER ALERT: Either the property name [" + this_prop_name + "] or the property value [" + this_prop_value + "] are illegal.");
        return false;
       }

   }
}

//********************SetClass function **************************************************

//  Purpose:  Use to change the class of an object.
//            element id, class to change to
//
//  Date:     07/10/06
//  Changes:

//************************************************************************************************


function SetClass(element,newclass) {

 //alert("class change running for " + element + ". Change class to " + newclass);
   var this_object;
   var undefined;

   if (document.layers) {
     return false;
   }

   if (document.all && document.all["" + element + ""] != null)  this_object = document.all["" + element + ""];
   if (document.getElementById && document.getElementById("" + element + "") != null) this_object = document.getElementById("" + element + "");

   if (this_object == undefined) {
     alert("Something is wrong.  Either the browser detection failed or the id you passed was invalid");
     return false;
   }

   this_object.className = newclass;
}

//********************ChangeStyleRules function **************************************************

//  Purpose:  Use to change specific style elements of a class.  Must know the array number of
//            the class you which to change.  Can change more than one style element
//            element id, style property name, style property value
//            if sending more than on property name/value separate with ":"
//            must have the same number of names and values
//
//  Date:     09/06/06
//  Changes:

//************************************************************************************************


function ChangeStyleRules(crules_array_num,prop1,prop2) {

   var theRules
   var undefined;

   if (document.styleSheets[0].cssRules) theRules = document.styleSheets[0].cssRules
   if (document.styleSheets[0].rules) theRules = document.styleSheets[0].rules

   for (var a = 1; a < ChangeStyleRules.arguments.length;a++) {

       prop = ChangeStyleRules.arguments[a].split(":");
       this_prop_name = prop[0];
       this_prop_value = prop[1];

       try {
         theRules[crules_array_num].style[""+this_prop_name+""] = this_prop_value;
       }
       catch(e) {
        alert("PROGRAMMER ALERT: Either the property name [" + this_prop_name + "] or the property value [" + this_prop_value + "] are illegal.");
        return false;
       }
   }
}

//********************CheckArray function ***************************
//
//Purpose:  allows you to check an array to see if an item already exists
//          arguments are:  array_object - the object to add
//                          array_name - the array you want to add to
//          returns true if found and false if not
//Date:     09/06/06
//Changes:
//
//****************************************************************


function CheckArray(array_object,array_name) {

   for (var a = 0; a < array_name.length;a++) {

      object_found = false;
      add_object = array_name[a];

      if (array_object == add_object) {
          object_found = true;
          return true;
      }
   }

  if (object_found == false) return false;
}



//********************AddOnLoad function **************************************************

//  Purpose:  add functions to the MyLoad array or capture existing window.onload
//            functions, remap them to MyOnLoad and add them to the array
//
//  Date:     07/10/06
//  Changes:
//*****************************************************************************************

function AddOnLoad(f) {

   checkit = CheckArray(f,"MyLoadArray");
   if (checkit == true) return false;

        if  (window.onload) {
                if (window.onload != MyOnLoad) {
                        MyLoadArray[MyLoadArray.length] = window.onload;
                        window.onload = MyOnLoad;
                }
        MyLoadArray[MyLoadArray.length] = f;
        } else {
          window.onload = f;
        }
}

//********************MyOnLoad function **************************************************

//  Purpose:  Run through the Myload array when the window loads
//
//  Date:     07/10/06
//  Changes:
//*****************************************************************************************

function MyOnLoad() {
        for (var i=0;i<MyLoadArray.length;i++) {
                MyLoadArray[i]();
        }
  return true;
}

//place focus on first empty input or on submit button
function IndexOnLoad() {

   if (document.forms["cfmclogin"] != undefined) {

     FORM = document.cfmclogin;
     runit();
     if (document.forms.CookieMgr != undefined) cookie_manager();
   }

   for (var a = 0; a < FORM.length; a++) {

       element = FORM.elements[a];

       if (element.type == undefined) continue;

       if (element.type != "hidden" && (element.value.length < 1 || element.type == "submit"))   {
           element.focus();
           element.select();
           break;
       }
   }
   window_loaded = true;
}

AddOnLoad(IndexOnLoad);

//********************AddOnsubmit function **************************************************

//  Purpose:  add functions to the MySubmit array or captures existing window.onsubmit
//            functions, remap them to MySubmit and add them to the array
//
//  Date:     07/10/06
//  Changes:
//*****************************************************************************************

function AddOnSubmit(f) {

    var check_object = CheckArray(f,"MySubmitArray");
    if (check_object == true) return false;

     for (var a = 0; a < document.forms.length;a++) {
        this_form = document.forms[a];
      if (this_form.onsubmit) {
         if (this_form.onsubmit != MyOnSubmit) {
                MySubmitArray[MySubmitArray.length] = this_form.onsubmit;
                MyOnSubmit = this_form.onsubmit;
         }
         MySubmitArray[MySubmitArray.length] = f;
      } else {
         MySubmitArray[MySubmitArray.length] = f;
         this_form.onsubmit = MyOnSubmit;
      }
    }
}

//********************MyOnSubmit function **************************************************

//  Purpose:  Run through the MySubmit array when the page is submitted.
//            Return false if the function being run returns false (to stop the submit)
//  Note:     if multiple forms on the page you will need to point them at MySubmit
//
//  Date:     07/10/06
//  Changes:
//*****************************************************************************************

function MyOnSubmit() {

        for (var i=0;i<MySubmitArray.length;i++) {
                var sub_ok = MySubmitArray[i]();
                if (sub_ok == false) {
                  return false;
                } 
        }
  return true;
}

//run certain functions if form is automatically submitted
function CfmcIndexSubmit() {

    pass_query();
    if (oreos && !have_cookie) set_cookie(life);
    //alert(submit_ok);
    if (popup && submit_ok) popopen();

return true;
}

AddOnSubmit(CfmcIndexSubmit);

function MakeReadOnly() {

      if (document.forms[0].elements["PASSWORD"] != null && document.forms[0].elements["PASSWORD"].value.length > 0) document.forms[0].elements["PASSWORD"].readOnly = true;
      if (document.forms[0].elements["password"] != null && document.forms[0].elements["password"].value.length > 0) document.forms[0].elements["password"].readOnly = true;
      if (document.forms[0].elements["NAME"] != null && document.forms[0].elements["NAME"].value.length > 0) document.forms[0].elements["NAME"].readOnly = true;
      if (document.forms[0].elements["name"] == null) {
         if (document.forms[0].elements["name"] != null && document.forms[0].elements["name"].value.length > 0) document.forms[0].elements["name"].readOnly = true;
      }
      if (document.forms[0].elements["booth"] != null  && document.forms[0].elements["booth"].value.length > 0) document.forms[0].elements["booth"].readOnly = true;
      if (document.forms[0].elements["special_types"] != null && document.forms[0].elements["special_types"].value.length) document.forms[0].elements["special_types"].readOnly = true;
      if (document.forms[0].elements["extn"] != null  && document.forms[0].elements["extn"].value.length > 0) document.forms[0].elements["extn"].readOnly = true;      
      if (document.forms[0].elements["timezone"] != null && document.forms[0].elements["timezone"].value.length > 0) document.forms[0].elements["timezone"].readOnly = true;
      if (document.forms[0].elements["soundchannel"] != null && document.forms[0].elements["soundchannel"].value.length > 0) document.forms[0].elements["soundchannel"].readOnly = true;      
return true;
}