///////////////////////////////////////////////////////////////////////////
// Making changes to the JavaScript below violates your CfMC support
// agreement.  DO NOT MAKE CHANGES TO THIS SCRIPT!
///////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//
// initial.js - javascript for index.html
//   written by   - ??????? cbova
//   last updated - 30nov01 cbova - for frames
//
////////////////////////////////////////////////////////////
// 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 undefined;
var oreos = false, where = "!!!";
var popup = false;
var start = false;
var first = "cookies";
var life  = 30;
var FORM;
var popit;

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

/////////////////////////////////////////////////////////////
///Set the variable based on user settings if they exist
/////////////////////////////////////////////////////////////

if (FORM.settings != null && FORM.settings != undefined) {

 if (user_use_autostart  != undefined) use_autostart = user_use_autostart;
 if (user_use_popwindows != undefined) use_popwindows = user_use_popwindows;
 if (user_use_cookies    != undefined) use_cookies = user_use_cookies;
 if (user_login_from  != undefined) login_from = user_login_from;
 if (user_cookie_lifetime != undefined) {
     life  = user_cookie_lifetime;
     cookie_lifetime  = user_cookie_lifetime;
 }    
 if (user_xsize   != undefined) xsize = user_xsize;
 if (user_ysize   != undefined) ysize = user_ysize;
 if (user_xcorner != undefined) xcorner = user_xcorner;
 if (user_ycorner != undefined) ycorner = user_ycorner;
}
////////////////////////////////////////////////////////////
// this is the actual thing
////////////////////////////////////////////////////////////

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

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

////////////////////////////////////////////////////////////
// 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;
   var have_cookie = 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 = "cookie: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) {
      //alert(oreos + " " + have_cookie);
      if (oreos && !have_cookie) set_cfmc_cookie(life);
      pass_query();
      
      if (popup) popit = popopen();

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


   FORM.onsubmit = function() {
   
      pass_query();   
      if (oreos && !have_cookie) set_cookie(life);
      if (popup) popopen();
 
   }
}

////////////////////////////////////////////////////////////
// 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"}
   
   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");
   var passwd = getvalue(query, "password");
   var id     = getvalue(query, "id");
   var pid    = getvalue(query, "pid");

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

   if (id.length > 0) {
      name = "respondent";
      passwd = id;
   }
   
   if (pid.length > 0) {
       name = "respondent";
       passwd = pid;
   }

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

   fillout_form(name, passwd);

      if (document.forms[0].PASSWORD != null) document.forms[0].PASSWORD.readOnly = true;
      if (document.forms[0].password != null) document.forms[0].password.readOnly = true;
      if (document.forms[0].NAME != null) document.forms[0].NAME.readOnly = true;
      if (document.forms[0].name != null) document.forms[0].name.readOnly = true;
  
   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;
   }     

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

   if (document.forms[0].PASSWORD != null) document.forms[0].PASSWORD.readOnly = true;
   if (document.forms[0].password != null) document.forms[0].password.readOnly = true;
   if (document.forms[0].NAME != null) document.forms[0].NAME.readOnly = true;
   if (document.forms[0].name != null) document.forms[0].name.readOnly = true;

   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");
   if (N != undefined) N.value = name;
   if (P != 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;
}


window.onload=function() {

   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;
       }
   }
}   


function pass_query() {
      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;
}