/* static variables */
ckvid_s = '';
ckset_s = '';
gg_map = '';
gg_map_icon_no = 0;
gg_map_slc = [];
gg_map_walk_icon_grp = 0;
gg_map_walk_icon_grp_names = ['icong', 'iconb', 'icony', 'iconp', 'iconw'];
gg_markers = [];
gg_bad_markers = [];
gg_slc_markers = [];
gg_slc_markers_renumber = false;
gg_polygons = [];
gl_pselem = '';
/* ======================================================================= */
/* log on check */
function vlogon(lfld, errdesc, prvrtn)
{
var x = eid(lfld);
x.style.backgroundColor = "white";
x.value = Trim(x.value).toLowerCase();
if (!prvrtn)
   return false;
if (x.value.length == 0) {
   x.style.backgroundColor = "yellow";
   x.focus();
   x.select();
   x = eid("logonerr");
   x.innerHTML = "<B>&nbsp;" + errdesc + "</B>";
   return false;
}
return true;
}
/* ======================================================================= */
/* display (true)/undisplay (false) loading button */
function setloadbutton(loading, loadtext)
{
var x = eid('logoutbutton');
try {
    if (loading) {
       if (typeof(loadtext) == 'undefined')
          x.value = "Loading..";
       else
          x.value = loadtext;
       x.style.backgroundColor = "#71B8FF";
       x.disabled = true;
    } else {
       x.value = "Log Out";
       x.style.backgroundColor = "#FF8080";
       x.disabled = false;
    }
}
catch(e) {
}
}
/* ======================================================================= */
/* change in selection type */
function select_change()
{
if (eid('selectname').checked) {
   var nameset = "";
   var LDPRset = "none";
   eid('LDseli').value = "?";
   try {
       var x = eid('PRseli');
       x.style.display = "none";
       x.value = "?";
       eid('PRlabeli').style.display = "none";
   }
   catch(e) {
   }
} else {
  nameset = "none";
  LDPRset = "";
  eid('lastnamei').value = "";
}
eid('LDcell').style.display = LDPRset;
eid('PRcell').style.display = LDPRset;
eid('NAMEcell').style.display = nameset;
if (eid('selectname').checked)
   eid('lastnamei').focus();
try {
    eid('contentsBox').style.display = "none";
}
catch(e) {
}
try {
    eid('LDmaparea').style.display = "none";
}
catch(e) {
}
}
/* ======================================================================= */
/* validate user and password before submitting (returns true if ok) */
function logon_validate()
{
if (vlogon('password', 'No password was entered', vlogon('username', 'User ID must be entered', true)))
   return(true);
return(false);
}
/* ======================================================================= */
/* check for cookies enabled */
function cookies_enabled()
{
if (document.cookie == "") {
   document.cookie = "cookietest=ok";
   if (document.cookie == "") {
      eid('logonerr').innerHTML = "<B>Cookies must be enabled!</B>";
      return(false);
   }
}
}
/* ======================================================================= */
/* validate the last name selection */
function name_validate()
{
var x = eid('lastnamei');
var nametest = eid('NAMEcell').style.display;
if (eid('logoutbutton').value != "Logging Out" && nametest != "none") {
   x.style.backgroundColor = "white";
   x.value = Trim(x.value);
   var namearr = x.value.split(',');
   if (Trim(namearr[0]).length < 2) {
      x.style.backgroundColor = "yellow";
      x.focus();
      x.select();
      x = eid("lastnameerr");
      x.innerHTML = "<B>At least 2 characters must be entered for the last name.</B>";
      return false;
   }
}
if (eid('logoutbutton').value != 'Logging Out')
   setloadbutton(true);
return true;
}
/* ======================================================================= */
/* change tooltip message and make Refresh button visible */
function party_change(elemid, ttxpos, ttypos, ckobj)
{
var ckname = ckobj.id;
if (ckname == 'pUnregi') {  // unregistered registrant checked or unchecked
   if (ckobj.checked)       // if checked, must uncheck others before reloading page
      clr_rel_ck(ckobj, 'pDemi', 'pGrni', 'pNebi', 'pNoni', 'pRepi');
   post_logon.submit();
   return;
} else {      // if a party checked, must clear 'Unregistered' and refresh page
   var unrck = eid('pUnregi');
   if (unrck.checked) {
      unrck.checked = false;
      post_logon.submit();
      return;
   }
}
ttPartySlcNo = 1;
eid("refreshi").style.display = "";
try {
   tt.show(ttPartySlc[ttPartySlcNo],ttxpos, ttypos, eid(elemid), 'mastHead', ttPartySlcBColor[ttPartySlcNo]);
} catch(e) {}
}
/* ======================================================================= */
/* build and post link to LD or precinct map */
function set_map(slcElement)
{
   var mapdiv = eid('maparea');
   try {
     mapdiv.style.width = '';
     mapdiv.style.height = '';
   } catch(e) {}
   var sm = eid(slcElement);
   var smval = sm.options[sm.selectedIndex].value;
   if (smval == '?')
      smval = 'ALL';
   smval = encodeURIComponent(smval);
   switch(slcElement)
   {
      case 'LDseli':
// Don't need Image() object as can just write out HTML; but saved for example
// Useful to preload images for quick display on demand
        var smsrc1 = 'maps/LD_City_' + smval + '.jpg';
//    var img1 = new Image();
//    img1.src = smsrc1;
        var smarea = eid('LDmaparea');
    smarea.style.display = "";
        var smsrc2 = 'maps/LD_County_' + smval + '.jpg';
//    var img2 = new Image();
//    img2.src = smsrc2;
        smarea.innerHTML = '<IMG src="' + smsrc1 + '" style="border:6px double black;display:none" onload="this.style.display = \'\';">' +
       '<p><IMG src="' + smsrc2 + '" style="border:6px double black;display:none" onload="this.style.display = \'\';">';
       break;
      case 'PRseli':
        var smsrc1 = 'maps/' + smval + '.gif';
        var img1 = new Image();
        img1.src = smsrc1;
        var smarea = eid('maparea');
        smarea.innerHTML = '<IMG src="' + smsrc1 + '" style="border:6px double black;display:none" onload="this.style.display = \'\';">';
        smarea.style.display = "";
        break;
   }
return true;
}
/* ======================================================================= */
/* build Google map */
function set_map_Google()
{
   var mapdiv = eid('maparea');
   var googlemapsts = eid('googlemapstsi');
   if (googlemapsts.value == '0') {
      googlemapsts.value = '2';
//      alert('The first call to Google Maps requires a refresh of the page.\nFuture calls will not, but each new page loaded may be\nslower as scripts are loaded from Google each time.\nLog off then back on to the site to stop this behavior.');
      post_logon.submit();
      return;
   }
   googlemapsts.value = '1';
   eid('precinct_bound_li').style.display='';
   google.load('maps', '2', {'callback' : set_map_Google_cb});
   return true;
}
function set_map_Google_cb()
{
   var mapdiv = eid('maparea');
   var googlemapsts = eid('googlemapstsi');
   if (GBrowserIsCompatible()) {
      mapdiv.style.width = '100%';
      mapdiv.style.height = '500px';
      var map = new GMap2(document.getElementById("maparea"));
      map.addControl(new GLargeMapControl());
      map.setCenter(new GLatLng(40.80145, -96.68855), 15);
      GEvent.addListener(map, 'zoomend', function(oldlevel, newlevel) {
              setTimeout(rmv_gmnoprint, 3000);  /* delay to not run until polygons are re-displayed */  });
   }
   var allelem = eid('datatbl').getElementsByTagName('td');
   var bounds = new GLatLngBounds();
   var pvline = -1;
   var addrstr = '';
   gg_map_icon_no = 0;
   var markeradded = false;
//   var aq = '';
   for (var gi = 0; gi < allelem.length; gi++) {
      var allelemobj = allelem[gi];
      var tdclsname = allelemobj.className;
      if (tdclsname.indexOf('vhhno') >= 0) {   /* household number */
         var vhhno = parseInt(allelemobj.innerHTML);
         if (vhhno != pvline) {
            if (addrstr != '') {
               var titledesc = vname + ' : ' + addrstr;
               var marker = createMarker(map, alat, along, titledesc);
               if (marker != null) {
                  map.addOverlay(marker);
                  bounds.extend(marker.getPoint());
                  markeradded = true;
               }
            }
            var vname = '';
            addrstr = '';
            pvline = vhhno;
         }
      }
      if (tdclsname.indexOf('vname') >= 0) {   /* name */
         if (vname != '')
            vname += ', ';
         else
            vname = vhhno + '. ';
         var namestr = allelemobj.innerHTML;
         namestr = namestr.replace('&amp;', '&');
         var apend = namestr.toLowerCase().indexOf('<span');
         if (apend >= 0)
            namestr = namestr.slice(0, apend);
         vname += namestr;
      }
      if (tdclsname.indexOf('vaddress') >= 0) {   /* address */
         var addrstr = allelemobj.innerHTML;
         addrstr = addrstr.replace('&amp;', '&');
//         aq = aq + '\n' + addrstr;
         var ap = addrstr.indexOf('`~`');
         if (ap == -1)
            addrstr = '';
         else {
            ap += 3;
            var apend = addrstr.indexOf('`', ap);
            if (apend == -1)
               addrstr = '';
            else {
               var alat = parseFloat(addrstr.slice(ap, apend));
               ap = apend + 1;
               apend = addrstr.indexOf('`', ap);
               if (apend == -1)
                  addrstr = '';
               else {
                  var along = parseFloat(addrstr.slice(ap, apend));
                  addrstr = addrstr.replace(/<span>/ig, '');
                  addrstr = addrstr.replace(/<\/span>/ig, '');
                  aend = addrstr.toLowerCase().indexOf('<span style');
                  if (aend >= 0)
                     addrstr = addrstr.slice(0, aend);
               }
            }
         }
      }
   }
   if (addrstr != '') {
      var titledesc = vname + ' : ' + addrstr;
      var marker = createMarker(map, alat, along, titledesc);
      if (marker != null) {
         map.addOverlay(marker);
         bounds.extend(marker.getPoint());
         markeradded = true;
      }
   }
   if (!markeradded) {
      mapdiv.innerHTML = '';
      mapdiv.style.width = '';
      mapdiv.style.height = '';
      alert('None of the addresses could be mapped.');
      return false;
   }
   map.setZoom(map.getBoundsZoomLevel(bounds));
   map.setCenter(bounds.getCenter());
   if (gg_bad_markers.length > 0) {
      var llb = map.getBounds();
      var llsw = llb.getSouthWest();
      var llne = llb.getNorthEast();
//   alert('SWlat= ' + llsw.lat());
//   alert('SWlong= ' + llsw.lng());
//   alert('NElat= ' + llne.lat());
//   alert('NElong= ' + llne.lng());
      var latdiff = Math.abs(llne.lat() - llsw.lat());
      var latoffset = latdiff / 100;
      var lngdiff = Math.abs(llne.lng() - llsw.lng());
      var lngoffset = lngdiff / 100;
//   alert('latdiff= ' + latdiff);
//   alert('lngdiff= ' + lngdiff);
//   alert('zoom= ' + map.getZoom());
      var lllat = llsw.lat() + 3 * latoffset;
      var lllng = llsw.lng() + lngoffset;
      for (gi = 0; gi < gg_bad_markers.length; gi++) {
         var bmarr = gg_bad_markers[gi].split('`');
//      alert('lat= ' + lllat);
//      alert('lng= ' + lllng);
         var marker = createMarker(map, lllat, lllng, bmarr[1], bmarr[0]);
         map.addOverlay(marker);
         lllng += 2 * lngoffset;
      }
   }

   gg_map = map;
   gg_map_icon_no = 0;
   gg_map_slc = [];
   gg_map_walk_icon_name = gg_map_walk_icon_grp_names[0];
   if (eid('precinct_boundaryi').checked) {
      var precinct = eid('PRseli').value;
      set_map_Google_border(true, precinct);
   }
   return true;
}

/* ======================================================================= */
/* display or remove precinct border on Google map */
function set_map_Google_border(display, precinct)
{
   if (display) {
      if (typeof(precinct) != 'undefined' && precinct != "ALL") {
         var randno = new Date().getTime();
         var httprqs = 'voter_get_precinct_bound_proc.php?precinct=' + encodeURIComponent(precinct) +
              '&__rand=' + randno;
         var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, set_map_Google_cb2);
      }
   } else {
      for (var ia = 0; ia < gg_polygons.length; ia++)
         gg_map.removeOverlay(gg_polygons[ia]);
   }
   return true;
}
var set_map_Google_cb2 = {
    success: function(o) {
       var xx = eid('maparea');
       var polygonopt = {
          clickable: false
       };
       gg_polygons.length = 0;
       var aa = (o.responseText).split('\n');
       var latlngs = [];
       for (var ia = 1; ia < aa.length - 2; ia++) {
          latlngs.length = 0;
          var ab = aa[ia].split(',');
          for (var ib = 0; ib < ab.length; ib++) {
             var ac = ab[ib].split(' ');
             var ac0 = ac[0];
             var ac1 = ac[1];
             if (ac0.substr(0,9) == 'POLYGON((') {
                ac0 = ac0.substr(9);
                var fillopac = .25;
                var fillcolor = '#A0FFFF';
             } else if (ac0.substr(0,1) == '(') {   /* hole in polygon */
                var polyg = new GPolygon(latlngs, '#FF0000', 5, .5, fillcolor, fillopac, polygonopt);
                gg_map.addOverlay(polyg);
                gg_polygons.push(polyg);
                latlngs.length = 0;
                ac0 = ac0.substr(1);
                var fillopac = .5;
                var fillcolor = '#000000';
             }
             var ac1l = ac1.length - 1;
             if (ac1.substr(ac1l,1) == ')') {
                ac1 = ac1.substr(0, ac1l);
                if (ac1.substr(--ac1l,1) == ')')
                   ac1 = ac1.substr(0, ac1l);
             }
             var point = new GLatLng(ac0, ac1);
             latlngs.push(point);
          }
          var polyg = new GPolygon(latlngs, '#FF0000', 5, .5, fillcolor, fillopac, polygonopt);
          gg_map.addOverlay(polyg);
          gg_polygons.push(polyg);
       }
       setTimeout(rmv_gmnoprint, 3000);  /* delay to not run until polygons are displayed */
    },
    failure: function(o) {
    },
    timeout: 15000
}
/* ======================================================================================== */
/* removes the "gmnoprint" class name from <div> element (prevents polygons from printing) */
function rmv_gmnoprint() {
   var divs = document.getElementsByTagName('div');
   for (var q = 0; q < divs.length; q++) {
      var qobj = divs[q];
      var qclass = qobj.className;
      if (qclass == 'gmnoprint') {
         qobj.className = '';
         break;     /* only remove the class name from first gmnoprint; that is the polygons */
      }
   }
}
/* ======================================================================= */
/* create a google map marker */
function createMarker(map, latitude, longitude, titlebox, icon_no)
{
   var iicon = new GIcon(G_DEFAULT_ICON);
   if (typeof(icon_no) == 'undefined')
      var icon_no_w = gg_map_icon_no;
   else
      var icon_no_w = icon_no - 1;
   if (++icon_no_w > 25)
      iicon.image = '../google_map_icons/iconr.png';
   else
      iicon.image = '../google_map_icons/iconr' + icon_no_w + '.png';
   if (latitude == 0) {
      gg_bad_markers.push(icon_no_w + '`' + titlebox);
      if (typeof(icon_no) == 'undefined')
         gg_map_icon_no = icon_no_w;
      return null;
   }
   iicon.printImage = iicon.image;
   iicon.mozPrintImage = iicon.image;
   var markeropt = {
       icon: iicon,
       title: titlebox
   };
   var point = new GLatLng(latitude, longitude);
   var marker = new GMarker(point, markeropt);
   GEvent.addListener(marker, 'mouseover', function() {
      var micon = marker.getIcon();
      if (eid('walkliststatusi').value == '1' &&
          micon.image.indexOf('iconr') >= 0) {
         var mpoint = marker.getPoint();
         var mtitle = marker.getTitle();
         var mnume = mtitle.indexOf('.');
         var mnum = parseInt(mtitle.slice(0, mnume));
         gg_map_slc.push(mnum);
         map.removeOverlay(marker)
         var wicon = new GIcon(G_DEFAULT_ICON);
         if (++gg_map_icon_no > 25) {
            gg_map_icon_no = 1;
            if (++gg_map_walk_icon_grp == gg_map_walk_icon_grp_names.length)
               --gg_map_walk_icon_grp;
            gg_map_walk_icon_name = gg_map_walk_icon_grp_names[gg_map_walk_icon_grp];
         }
         wicon.image = '../google_map_icons/' + gg_map_walk_icon_name + gg_map_icon_no + '.png';
         wicon.printImage = wicon.image;
         wicon.mozPrintImage = wicon.image;
         var mtitlediv = mtitle.indexOf('.');
         mtitle = icon_no_w + '.' + mtitle.substr(mtitlediv + 1);
         var newmarkeropt = {
            icon: wicon,
            title: mtitle
         };
         var newmark = new GMarker(mpoint, newmarkeropt);
         gg_slc_markers.push(newmark);
         map.addOverlay(newmark);
//         marker.setImage(iconurl);
         GEvent.addListener(newmark, 'click', function() {
            gg_slc_markers_renumber = true;
            for (var i = 0; i < gg_map_slc.length; i++) {
               if (gg_map_slc[i] == mnum) {
                  var j = i + 1;
                  while (j < gg_map_slc.length) {
                     gg_map_slc[i] = gg_map_slc[j];
                     gg_slc_markers[i++] = gg_slc_markers[j++];
                  }
                  gg_map_slc.pop();
                  gg_slc_markers.pop();
                  break;
               }
            }
            map.removeOverlay(newmark);
            setTimeout('createMarkerDelay(gg_map, ' + latitude + ',' + longitude + ', \'' +
                titlebox + '\',' + icon_no_w + ')', 2000);
            

         });
      }
   });
   gg_markers.push(marker);
   if (typeof(icon_no) == 'undefined')
      gg_map_icon_no = icon_no_w;
   return marker;
}
//  Delay creation of marker and add to map; allows mouse to be moved first
function createMarkerDelay(map, latitude, longitude, titlebox, icon_no_w)
{
   var newmark2 = createMarker(map, latitude, longitude, titlebox, icon_no_w);
   map.addOverlay(newmark2);
   return true;
}
/* ======================================================================= */
/* change google select walk list to '1' (on) */
function setwalklist(button)
{
   var walklist =  eid('walkliststatusi');
   if (walklist.value == '0') {
      walklist.value = '1';
      button.value = 'Post\nWalk List';
      eid('downloadi').style.visibility = 'hidden';  /* download would do entire list, not selected, so disable */
   } else if (walklist.value == '1') {
      try {
         eid('voter_totali').style.display = 'none';  /* Totals may be invalid if entries deleted */
      } catch(e) {}
      setloadbutton(true, 'Sorting..');
      eid('walklisthelpi').style.display = 'none';
      button.style.display = 'none';
      button.value = 'Walk\nRouting';
      walklist.value = '0';
      eid('getgooglemapi').style.display = 'none';
      var neword = new Array();
      for (var i = 0; i < gg_map_slc.length; i++)
         neword[gg_map_slc[i]] = i + 1;
      var vhhnopos = new Array();
      var vhhnoarr = new Array();
      var vhhnosort = new Array();
      var vlmap = new Array();
      var vl = 0;
      var allelem = eid('datatbl').getElementsByTagName('td');
      var supcolor = ['green', 'blue', '#D2D200', '#F161D0', 'black'];
      for (var gi = 0; gi < allelem.length; gi++) {  /* reassign household numbers in walking order */
         var allelemobj = allelem[gi];
         var tdclsname = allelemobj.className;
         if (tdclsname.indexOf('vhhno') >= 0) {
            vhhnopos[gi] = gi;
            vhhnoarr.push(gi);
            vhhnosort.push(gi);
            var vhhno = parseInt(allelemobj.innerHTML);
            var newordval = neword[vhhno];
            if (typeof(newordval) == 'undefined') { /* not selected on walk route */
               allelemobj.innerHTML = '';
               vlmap[vl] = 30000;
            } else {
               var supseg = Math.floor((newordval - 1)/25);
               if (supseg >= supcolor.length)
                  supseg = supcolor.length - 1;
               var supsegnum = (newordval - 1) % 25 + 1;
               allelemobj.innerHTML = '<span style="color:' + supcolor[supseg] + ';"><sup>(' +
                   supsegnum + ')</sup></span> ' + newordval;
               vlmap[vl] = newordval;
            }
            ++vl;
         }
      }
      do {   /* sort line pointers by new lines numbers (bubble sort) */
         var resort = false;
         for (gi = 0; gi < vhhnosort.length - 1; gi++) {
            var n1val = vlmap[gi];
            var n2val = vlmap[gi + 1];
            if (parseInt(n1val) > parseInt(n2val)) {
               resort = true;
               vlmap[gi] = n2val;
               vlmap[gi + 1] = n1val;
               var vhwrk = vhhnosort[gi];
               vhhnosort[gi] = vhhnosort[gi + 1];
               vhhnosort[gi + 1] = vhwrk;
            }
         }
      } while(resort);
      
      for (gi = 0; gi < gg_markers.length; gi++) { /* remove non-selected markers */
         try {
            gg_map.removeOverlay(gg_markers[gi]);
         } catch(e) {}
      }
      if (gg_slc_markers_renumber) {  /* renumber selected markers */
         gg_map_icon_no = 0;
         gg_map_walk_icon_grp = 0;
         for (gi = 0; gi < gg_slc_markers.length; gi++) {
            try {
               var marker = gg_slc_markers[gi];
               var mpoint = marker.getPoint();
               var mtitle = marker.getTitle();
               gg_map.removeOverlay(marker);
               var wicon = new GIcon(G_DEFAULT_ICON);
               if (++gg_map_icon_no > 25) {
                  gg_map_icon_no = 1;
                  if (++gg_map_walk_icon_grp == gg_map_walk_icon_grp_names.length)
                     --gg_map_walk_icon_grp;
                  gg_map_walk_icon_name = gg_map_walk_icon_grp_names[gg_map_walk_icon_grp];
               }
               wicon.image = '../google_map_icons/' + gg_map_walk_icon_name + gg_map_icon_no + '.png';
               wicon.printImage = wicon.image;
               wicon.mozPrintImage = wicon.image;
               var mtitlediv = mtitle.indexOf('.');
               mtitle = gg_map_icon_no + '.' + mtitle.substr(mtitlediv + 1);
               var newmarkeropt = {
                  icon: wicon,
                  title: mtitle
               };
               var newmark = new GMarker(mpoint, newmarkeropt);
               gg_map.addOverlay(newmark);
            } catch(e) {}
         }
      }
      for (gi = 0; gi < vhhnoarr.length; gi++) {  /* reorder table */
         var n1 = vhhnoarr[gi];
         var ns = vhhnosort[gi];
         if (n1 != ns) {
            var n1obj = allelem[vhhnopos[n1]];
            var nsobj = allelem[vhhnopos[ns]];
            var t1lineobj = n1obj.parentNode.parentNode;
            var t2lineobj = nsobj.parentNode.parentNode;
            var t1html = t1lineobj.innerHTML;
            var t2html = t2lineobj.innerHTML;
            replaceHTML(t1lineobj, t2html);  /* swap actual lines in HTML table */
            replaceHTML(t2lineobj, t1html);
            var vhhnowrk = vhhnopos[n1];   /* indicate swap in position array */
            vhhnopos[n1] = vhhnopos[ns];
            vhhnopos[ns] = vhhnowrk;
            for (gic = gi + 1; gic < vhhnoarr.length; gic++) {  /* swap td position array elements */
               if (vhhnoarr[gic] == ns) {
                  vhhnoarr[gi] = ns;
                  vhhnoarr[gic] = n1;
                  break;
               }
            }
         }
      }
      var lcolorFF = ['rgb(189, 236, 217)', 'rgb(221, 244, 235)'];  /* alternating line background colors (Firefox) */
      var lcolorIE = ['#bdecd9', '#ddf4eb'];  /* alternating line background colors (Internet Explorer) */
      var lc = -1;
      var removeobj = new Array();
      var pvval = '@@@@@@';
      for (var x in vhhnopos) {  /* reassign background color */
         n1obj = allelem[x];
         n1val = n1obj.innerHTML;
         if (n1val == "") {   /* save unselected line objects */
            removeobj.push(n1obj.id);
            continue;
         }
         if (n1val != pvval) {
            ++lc;
            if (lc >= lcolorFF.length)
               lc = 0;
            pvval = n1val;
         }
         t1lineobj = n1obj.parentNode;
         if (t1lineobj.style.backgroundColor == lcolorFF[0] ||
             t1lineobj.style.backgroundColor == lcolorFF[1] ||
             t1lineobj.style.backgroundColor == lcolorIE[0] ||
             t1lineobj.style.backgroundColor == lcolorIE[1])
            t1lineobj.style.backgroundColor = lcolorFF[lc];
      }
      x = removeobj.length;     /* remove unselected lines */
      while (x-- > 0) {
         n1obj = eid(removeobj[x]).parentNode;
         n1obj.parentNode.removeChild(n1obj);
      }
      setloadbutton(false);
   }
}
/* ======================================================================= */
/* voter grade tooltip showing general/primary breakout */
function vtt(tblElement, vgen, vpri)
{
  var vttmsg = 'General: ' + vgen + '<br>Primary:&nbsp;&nbsp;' + vpri;
  try {
     tt.show(vttmsg, 50, 0, tblElement, 'contentsBox');
  } catch(e) {}
}
/* ======================================================================= */
/* get complete voter election info; output in a popup */
var get_velec_cb = {
    success: function(o) {
       var wtext = Trim(o.responseText);
       var xpos = Number(wtext.substr(0,4)) + 100;
       var w = window.open('', 'Election_History', 'scrollbars=yes,height=550,width=500,top=0,left=' + xpos);
       w.document.write(wtext.substr(4));
       w.document.close();
       setloadbutton(false);
       w.focus();
    },
    failure: function(o) {
       setloadbutton(false);
    },
    timeout: 30000
}
function get_velec(elem, voterid) {
   setloadbutton(true);
   elemX = getX(elem);
   var randno = new Date().getTime();
   var httprqs = 'voter_getelec.php?velec=' + voterid + '&xpos=' + elemX + '&__rand=' + randno;
   var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, get_velec_cb);
}
/* ======================================================================= */
/* filter political subdivision changed */
function poldiv_chg(fldobj)
{
   if (fldobj.value == '') {
      eid('td_poldivi').innerHTML = '';
      return true;
   }
   eid('td_poldivi').innerHTML = '<span style="font-weight:bold;font-style:italic;color:blue;">Getting values...</span>';
   poldiv_values(fldobj.value);
   return true;
}

/* ======================================================================= */
/* get distinct values for a political subdivision (HTML select/option) */
var poldiv_values_cb = {
    success: function(o) {
       eid('td_poldivi').innerHTML = o.responseText;
    },
    failure: function(o) {
       eid('td_poldivi').innerHTML = '<SPAN style="color:red;">Request failed (possible timeout)</SPAN>';
    },
    timeout: 15000
}
function poldiv_values(pdfld)
{
   var randno = new Date().getTime();
   var httprqs = 'voter_poldiv_values.php?pdfld=' + encodeURIComponent(pdfld) + '&__rand=' + randno;
   var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, poldiv_values_cb);
}
/* ======================================================================= */
/* get election list (HTML select/option) */
var eleclist_values_cb = {
    success: function(o) {
       eid('td_eleclisti').innerHTML = o.responseText;
       eid('eleclistopti').style.display = '';
       eid('eleclistanyi').checked = true;
    },
    failure: function(o) {
       eid('td_eleclisti').innerHTML = '<SPAN style="color:red;">Request failed (possible timeout)</SPAN>';
    },
    timeout: 15000
}
function eleclist_values()
{
   var randno = new Date().getTime();
   var httprqs = 'voter_election_list.php?__rand=' + randno;
   var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, eleclist_values_cb);
}
/* ======================================================================= */
/* get group list (HTML select/option) */
var grouplist_values_cb = {
    success: function(o) {
       eid('td_grouplisti').innerHTML = o.responseText;
    },
    failure: function(o) {
       eid('td_grouplisti').innerHTML = '<SPAN style="color:red;">Request failed (possible timeout)</SPAN>';
    },
    timeout: 15000
}
function grouplist_values()
{
   var randno = new Date().getTime();
   var httprqs = 'voter_group_list.php?__rand=' + randno;
   var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, grouplist_values_cb);
}
/* ======================================================================= */
/* set the color of the group list selection */
function set_group_color(elemobj)
{
   if (elemobj.value == '')
   {
      elemobj.style.backgroundColor = rgb(255,255,192);
      elemobj.style.color = '';
   } else {
      elemobj.style.backgroundColor = 'blue';
      elemobj.style.color = 'white';
   }
}
/* ======================================================================= */
/* reset (clear) filter elements */
function reset_filter(allow_updating)
{
   var fa = new Array('elecgrade', 'elecgeneral', 'elecprimary', 'age', 'regdate', 'propvalue',
               'early_vote_date');  /* range fields */
   var fc = new Array('alwaysinclckf', 'ldleaderf', 'ldassistantf', 'ldteamf','precinctleaderf', 'precinctteamf',
                      'countypartyf', 'ccexecf', 'ccdelegatef', 'ccalternatef', 'caucusdelegatef',
                      'caucusalternatef', 'caucusattendeef', 'emailexistf', 'emailnoexistf',
                      'maleonlyf', 'femaleonlyf', 'omitaptf', 'onarterialf', 'phoneexistf', 'cityf', 'ruralf',
                      'early_vote_yf', 'early_vote_nf', 'VBM_returned_yf', 'VBM_returned_nf');  /* checkbox fields */
   for (var fi = 0; fi < fa.length; fi++) {
      var fld = fa[fi];
      try {
         var n = eid(fld + 'Compi');
      } catch(e) {
         continue;
      }
      if (n == null)
         continue;
      n.value = '';
      n.selectedIndex = 0;
      eid(fld + 'Vali').value = '';
      if (fld == 'regdate' || fld == 'early_vote_date')
         eid(fld + 'Vali').value = 'mm/dd/yyyy';
      n = eid(fld + '2Compi');
      n.value = '';
      n.selectedIndex = 0;
      eid(fld + '2Vali').value = '';
      if (fld == 'regdate' || fld == 'early_vote_date')
         eid(fld + '2Vali').value = 'mm/dd/yyyy';
   }
   eid('regdateAndOri').selectedIndex = 0;
   eid('poldivi').selectedIndex = 0;
   eid('td_poldivi').innerHTML = '';
   eid('eleclistopti').style.display = 'none';
   eid('eleclistnumfi').value = '';
   
/* clear election filter */
   eid('td_eleclisti').innerHTML = '<input name="eleclistslc" value="Click to select" type="button" onclick="eleclist_values();">';
   eid('eleclistalli').value = '';
/* clear voter group filter */
   if (allow_updating > 0)
   {
      eid('td_grouplisti').innerHTML = 'Group...&nbsp;&nbsp;<input name="grouplistslc" value="Click to select" type="button" onclick="grouplist_values();">';
      eid('grouplistalli').value = '';    
   }   
   
   for (fi = 0; fi < fc.length; fi++)
      eid(fc[fi] + 'i').checked = false;
}
/* ======================================================================= */
/* save filter elements and refresh if content present; hide filter box */
function save_filter()
{
   var fl=eid('filteri');
   fl.value='Filter';
   fl.className='noprint';
   fl.style.backgroundColor='';
   var filter = false;
   var fa = new Array('elecgrade', 'elecgeneral', 'elecprimary', 'age', 'regdate', 'propvalue',
         'early_vote_date');  /* range fields */
   var fv = new Array('', '', '', '', 'mm/dd/yyyy', '', 'mm/dd/yyyy'); /* alternate default values */
   var fc = new Array('alwaysinclckf', 'ldleaderf', 'ldassistantf', 'ldteamf','precinctleaderf', 'precinctteamf',
                      'countypartyf', 'ccexecf', 'ccdelegatef', 'ccalternatef', 'caucusdelegatef',
                      'caucusalternatef', 'caucusattendeef', 'emailexistf', 'emailnoexistf',
                      'maleonlyf', 'femaleonlyf', 'omitaptf', 'onarterialf', 'phoneexistf', 'cityf', 'ruralf',
                      'early_vote_yf', 'early_vote_nf', 'VBM_returned_yf', 'VBM_returned_nf');  /* checkbox fields */
   for (var fi = 0; fi < fa.length; fi++) {
      var fld = fa[fi];
      try {
         var f = eid(fld + 'Vali');
      } catch(e) {
         continue;
      }
      if (f == null)
         continue;
      f.value = Trim(f.value);
      if (eid(fld + 'Compi').value != '' && f.value != '' && f.value != fv[fi])
         filter = true;
   }
   try {
      if (eid('poldivvali').selectedIndex > 0)
         filter = true;
   } catch(e) {}
   for (fi = 0; fi < fc.length; fi++)
      if (eid(fc[fi] + 'i').checked)
         filter = true;
   if (filter) {
      fl.value='Filtered';
      fl.className='print';
      fl.style.backgroundColor=rgb(255,204,204);
   }
   eid('filterboxi').style.display = 'none';
/* add or remove ALL option from LD and precinct selections */
/* NOTE: *CS (caucus site) was removed from the LD list */
/*       If put back, must change the length/option position of ALL from 1 to 2 */
   var ALLpos = 1;
   var slelem = eid('LDseli');    /* LD selector */
   if (filter) {
      if (slelem.length <= ALLpos) {
         var alloptelem = document.createElement('option');
         alloptelem.text = 'ALL';
         alloptelem.value = 'ALL';
         try {slelem.add(alloptelem, null);}
         catch(e) {slelem.add(alloptelem, 0);}  /* IE requires index (not in compliance with DOM) */
      } else if (slelem.options[ALLpos].value != 'ALL') {
         var alloptelem = document.createElement('option');
         alloptelem.text = 'ALL';
         alloptelem.value = 'ALL';
         try {slelem.add(alloptelem, slelem.options[ALLpos]);}
         catch(e) {slelem.add(alloptelem, ALLpos); }     /* IE requires index (not in compliance with DOM) */
      }
   }
   else if (slelem.length > ALLpos && slelem.options[ALLpos].value == 'ALL') {
      if (slelem.selectedIndex == ALLpos)
         slelem.selectedIndex = 0;
      slelem.remove(ALLpos);
   }
   if (eid('PRseli')) {             /* precinct selector (if exists) */
      var slelem = eid('PRseli');
      if (filter) {
         if (slelem.length <= ALLpos) {
            var alloptelem = document.createElement('option');
            alloptelem.text = 'ALL';
            alloptelem.value = 'ALL';
            try {slelem.add(alloptelem, null);}
            catch(e) {slelem.add(alloptelem, 0);}  /* IE requires index (not in compliance with DOM) */
         } else if (slelem.options[ALLpos].value != 'ALL') {
            var alloptelem = document.createElement('option');
            alloptelem.text = 'ALL';
            alloptelem.value = 'ALL';
            try {slelem.add(alloptelem, slelem.options[ALLpos]);}
            catch(e) {slelem.add(alloptelem, ALLpos); }     /* IE requires index (not in compliance with DOM) */
         }
      }
      else if (slelem.length > ALLpos && slelem.options[ALLpos].value == 'ALL') {
         if (slelem.selectedIndex == ALLpos)
            slelem.selectedIndex = 0;
         slelem.remove(ALLpos);
      }
   }
   if (eid('contentsBox')) {
      setloadbutton(true);
      post_logon.submit();
   }
}
/* ======================================================================= */
/* set show_caucus_precincts checkbox and hidden field */
function set_show_caucus_precincts(val, onchange)
{
   if (!onchange) { /* initialize to post values */
      var v = val;
      if (v == 'false')
         v = false;
      eid('showcaucusprecinctshi').value = v;
      eid('showcaucusprecinctsi').checked = v;
   } else {  /* change form field to the element's value and submit form */
      eid('showcaucusprecinctshi').value = val.checked;
      post_logon.submit();
   }
}
/* ======================================================================= */
/*  update a voter record; display the update screen  */
var updtvoter_cb = {
    success: function(o) {
       var udiv = eid('voter_updatei');
       udiv.innerHTML += o.responseText;
       var p = o.responseText.indexOf('<SCRIPT>');   /* execute script at end to load existing data */
       if (p != -1) {
          var pe = o.responseText.indexOf('</SCRIPT>');
          var pe = pe - p - 8;
          if (pe > 0)
             eval(o.responseText.substr(p + 8, pe));
        }
    },
    failure: function(o) {
       var udiv = eid('voter_updatei');
       udiv.innerHTML += '<br><b style="color:red;">Request timed out.</b>&nbsp;&nbsp;<input style="color: white; background-color: red; font-weight: bold;" onclick="postvoter(false);" name="cancelvoter" value="Cancel" type="button">';
    },
    timeout: 12000
}
function updtvoter(elemobj, name, showzip, select, vfphone, viewonly, convention, ccmeeting)
{
   var voterid = elemobj.value;
   var xpos = getX(elemobj);
   var udiv = eid('voter_updatei');
   udiv.style.display = ''; /* NOTE: with IE must set display on first or border didn't display until scroll */
   /* build header */
   udiv.innerHTML = '<B>' + name + '</B>';
   udiv.innerHTML += '&nbsp;&nbsp;<SPAN style="font-size:90%;font-style:italic;">(' + voterid + ')</SPAN>';
//   udiv.style.left = xpos + elemobj.offsetWidth;  /* was used to center; now just fix to 50px */
   /* get record for voter id; also pass any table line fields/styles that must be restored */
   var lineno_id = 'tdline_' + voterid + 'i';
   var lineno = eid(lineno_id).innerHTML;
   var trid = 'tr_' + voterid + 'i';
   var trbgcolorid = 'trbgcolor_' + voterid + 'i';
   var lcolor = eid(trid).style.color;
   var bgcolor = eid(trbgcolorid).value;
   var randno = new Date().getTime();
   var httprqs = 'voter_update_proc.php?opt=get&voter_id=' + voterid + '&t__lineno=' + lineno +
                     '&t__lcolor=' + encodeURIComponent(lcolor) + '&t__bgcolor=' + encodeURIComponent(bgcolor) +
                     '&t__showzip=' + showzip + '&t__select=' + select + '&t__convention=' + convention +
                     '&t__cc_meeting=' + ccmeeting +
                     '&t__vfphone=' + vfphone + '&t__viewonly=' + viewonly + '&__rand=' + randno;
   var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, updtvoter_cb);
}
/* ======================================================================= */
/*  mark a phone number as verified by copying to the primary phone  */
/*  phone number must be in the xxx-xxx-xxxx format  */
function phone_verified(phonenum)
{
   if (eid('do_not_calli').checked)  /* ignore if do-not-call checked */
      return false;
   var phonelo = eid('primary_phone_li');
   var phonemo = eid('primary_phone_mi');
   var phonero = eid('primary_phone_ri');
   if (Trim(phonelo.value).length != 0 || Trim(phonemo.value).length != 0 ||
       Trim(phonero.value).length != 0) {
       if (!(confirm('A primary phone number exists. Click OK if you wish to replace it with the verified phone number.')))
          return false;
   }
   phonelo.value = phonenum.substr(0,3);
   phonemo.value = phonenum.substr(4,3);
   phonero.value = phonenum.substr(8,4);
   eid('primary_phone_typei').value = '';
}
/* ======================================================================= */
/*  disable/enable phone fields based on do-not-call field  */
function donotcall_fset()
{
   var phoneflds = new Array('primary_phone','alt_phone','alt2_phone');  /* phone fields */
   var disval = '';
   var bgcolor = '';
   if (eid('do_not_calli').checked) {
      disval = 'disabled';
      bgcolor = 'gray';
   }
   for (var i = 0; i < phoneflds.length; i++) {
      var fldobj = eid(phoneflds[i] + '_li');
      fldobj.disabled = disval;
      fldobj.style.backgroundColor = bgcolor;
      fldobj = eid(phoneflds[i] + '_mi');
      fldobj.disabled = disval;
      fldobj.style.backgroundColor = bgcolor;
      fldobj = eid(phoneflds[i] + '_ri');
      fldobj.disabled = disval;
      fldobj.style.backgroundColor = bgcolor;
      fldobj = eid(phoneflds[i] + '_typei');
      fldobj.disabled = disval;
      fldobj.style.backgroundColor = bgcolor;
   }
}
/* ======================================================================= */
/*  post updates to voter record  */
var postvoter_cb = {
    success: function(o) {
       var p = o.responseText.indexOf('<<SUCCESS>>');    /* success of update or delete */
       if (p >= 0) {
          p = o.responseText.indexOf('<<', ++p);
          p += 2;
          var px = o.responseText.indexOf('>>', p);
          var lineid = 'tb_' + o.responseText.substr(p, px - p) + 'i';
          replaceHTML(eid(lineid), o.responseText.substr(px + 2));
          eid('voter_updatei').style.display = 'none';
          try {
             eid('lastnamei').focus();
             eid('lastnamei').select();
          } catch(e) {}
       }
       else
          eid('record_updt_erri').innerHTML = o.responseText;
    },
    failure: function(o) {
       var udiv = eid('voter_updatei');
       udiv.innerHTML = '<br><b style="color:red;">Request timed out.&nbsp;&nbsp;Update may or may not have succeeded.</b>&nbsp;&nbsp;<input style="color: white; background-color: red; font-weight: bold;" onclick="postvoter(false);" name="cancelvoter" value="Cancel" type="button">';
    },
    timeout: 15000
}
function postvoter(postrec, voterid, lineno, lcolor, bgcolor, showzip, select, convention, ccmeeting)
{
   var ckflds = new Array('LD_leader','LD_assistant','LD_team','precinct_leader','precinct_team',
                'CC_exec','CC_delegate','CC_alternate','CP_mbr','caucus_delegate',
                'caucus_alternate','caucus_attendee','newsletter_email','newsletter_mail',
                'elec_file_phone_bad','sb_phone_bad','do_not_call','early_vote','VBM_returned'); /* check box fields */
   var ckvals = new Array();   /* container array for check boxes */
   var radioflds = new Array('volunteer');  /* radio button fields */
   var radiovals = new Array();  /* container array for radio button fields */
   var phoneflds = new Array('primary_phone','alt_phone','alt2_phone');  /* phone fields */

   if (postrec) {
      var noerr = true;
      eid('record_updt_erri').innerHTML = '';
      for (var i = 0; i < 2; i++) {
         var errText = '';
         if (i == 0)
            var emailobj = eid('email_addri');
         else
            var emailobj = eid('email_addr_2i');
         emailobj.value = Trim(emailobj.value);
         if (emailobj.value.length > 0) {
            var sa = emailobj.value.indexOf('@');   /* one and only 1 @ */
            var sa2 = emailobj.value.lastIndexOf('@');
            var sd = emailobj.value.lastIndexOf('.');  /* a . must be after @ */
            var sb = emailobj.value.indexOf(' ');  /* no blanks */
            if (sa == -1 || sd == -1 || sa != sa2 || sd < sa || sb >= 0) {  /* bad e-mail format */
               noerr = false;
               errText = '<br>E-mail format is invalid.';
            }
         }
         setTblFldErr(emailobj, errText, 'red', '');
      }
      var nophoneerr = true;
      for(i = 0; i < phoneflds.length; i++) {
         var phonelo = eid(phoneflds[i] + '_li');
         var phonemo = eid(phoneflds[i] + '_mi');
         var phonero = eid(phoneflds[i] + '_ri');
         phonelo.value = Trim(phonelo.value);
         phonemo.value = Trim(phonemo.value);
         phonero.value = Trim(phonero.value);
         if (phonelo.value.length == 0 && phonemo.value.length == 0 && phonero.value.length == 0) {
            eid(phoneflds[i] + '_typei').value = '';
            continue;
         }
         if (phonelo.value.length == 3 && phonemo.value.length == 3 && phonero.value.length == 4)
            continue;
         nophoneerr = false;
         noerr = false;
      }
      var CPdues = eid('CP_dues_last_paidi');
      CPdues.value = Trim(CPdues.value);
      CPdues.style.color = '';
      if (CPdues.value.length != 0 && CPdues.value.length != 6) {
         CPdues.style.color = 'red';
         noerr = false;
      }
      if (!nophoneerr)
         alert('At least one phone number is not correct.');
      if (!noerr)
         return(noerr);
      var nochecked = true;
      for (var i = 0; i < ckflds.length; i++) {
         ckvals[i] = '';
         try {  /* some fields are not always output */
            if (eid(ckflds[i] + 'i').checked) {
               ckvals[i] = '1';
               nochecked = false;
            }
         } catch(e) {}
      }
      var noradio = true;
      for (i = 0; i < radioflds.length; i++) {
         if ((radiovals[i] = getCheckedValue(radioflds[i])) != '')
            noradio = false;
      }
      var email_addr = Trim(eid('email_addri').value);
      var email_addr_2 = Trim(eid('email_addr_2i').value);
      var notes = Trim(eid('notesi').value);
      var notes = notes.replace(/\r/g, "");  /* ALL TEXTAREA FIELDS MUST HAVE \r REMOVED (RETURN ON NEWLINE)
                                                IE INSERTS THESE, NOT FIREFOX, ON NEW LINES */
      email_addr = email_addr.replace(/'/g, '\\\'');  /* replace all ' with \' */
      email_addr = '\'' + email_addr + '\'';    /* must quote all character fields */
      email_addr_2 = email_addr_2.replace(/'/g, '\\\'');  /* replace all ' with \' */
      email_addr_2 = '\'' + email_addr_2 + '\'';    /* must quote all character fields */
      notes = notes.replace(/'/g, '\\\'');  /* replace all ' with \' */
      notes = '\'' + notes + '\'';    /* must quote all character fields */
      httprqs_line = '&t__lineno=' + lineno + '&t__lcolor=' + encodeURIComponent(lcolor) + '&t__bgcolor=' +
         encodeURIComponent(bgcolor) +
         '&t__showzip=' + showzip + '&t__select=' + select +
         '&t__convention=' + convention + '&t__cc_meeting=' + ccmeeting;   /* fields necessary to rebuild voter table line */

/*  Change to always update, never delete  */
/*
      if (nochecked && email_addr.length == 2 && notes.length == 2) {  /* delete voter profile (email_addr is quoted) */
/*         var randno = new Date().getTime();
         var httprqs = 'voter_update_proc.php?opt=delete&voter_id=' + voterid + httprqs_line + '&__rand=' + randno;
         var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, postvoter_cb);
         return(true);
      }    */
      var randno = new Date().getTime();
      var CPduesfmt = '';
      if (CPdues.value.length == 6)
         CPduesfmt = CPdues.value.substr(0,4) + '-' + CPdues.value.substr(4,2) + '-01';
      var httprqs = 'voter_update_proc.php?opt=update&voter_id=' + voterid +
           '&email_addr=' + encodeURIComponent(email_addr) +
           '&email_addr_2=' + encodeURIComponent(email_addr_2) +
           '&notes=' + encodeURIComponent(notes) + httprqs_line +
           '&CP_dues_last_paid=\'' + CPduesfmt + '\'' + '&__rand=' + randno;
      for (i = 0; i < ckflds.length; i++)
         httprqs += '&' + ckflds[i] + '=' + ckvals[i];
      for (i = 0; i < radioflds.length; i++)
         httprqs += '&' + radioflds[i] + '=' + radiovals[i];
      for (i = 0; i < phoneflds.length; i++) {
         var pfname = phoneflds[i];
         httprqs += '&' + pfname + '=';
         if (Trim(eid(pfname + '_li').value).length > 0)
            httprqs += '\'' + eid(pfname + '_li').value + '-' +
                       eid(pfname + '_mi').value + '-' +
                       eid(pfname + '_ri').value + '\'';
         pfname += '_type';
         httprqs += '&' + pfname + '=\'' + eid(pfname + 'i').value + '\'';
      }
      /* Caucus candidate  */
      i = 0;
      httprqs += '&caucus_candidate=';
      while(true) {
         try {
            if (eid('caucus_candidate_' + i + 'i').checked) {
               httprqs += i;
               break;
            }
         }
         catch(e) {
            httprqs += '\'\'';
            break;
         }
         ++i;
      }
      var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, postvoter_cb);
      return(true);
   }
   eid('voter_updatei').style.display = 'none';
   try {
      eid('lastnamei').focus();
      eid('lastnamei').select();
   } catch(e) {}
}
/* ======================================================================= */
/*  change in check-in status  */
var ckinchg_cb = {
    success: function(o) {
       var ckref = eid('trckin_' + ckvid_s + 'i');
       var p = o.responseText.indexOf('<<SUCCESS>>');    /* success of update */
       if (p >= 0) {
          var vtr = eid('tr_' + ckvid_s + 'i');
          if (ckref.checked)
             vtr.style.backgroundColor = '#FF8080';      /* light red background indicates checked in */
          else {
             vtr.style.backgroundColor = eid('trbgcolor_' + ckvid_s + 'i').value;
             var vname = eid('tdname_' + ckvid_s + 'i').innerHTML;
             if (vname.indexOf('(exec') != -1)
                vtr.style.backgroundColor = '#E0E0E0';   /* CC exec background color*/
             else if (vname.indexOf('(delg') != -1)
                vtr.style.backgroundColor = '#AEE4F0';   /* CC delegate background color */
             else if (vname.indexOf('(alt') != -1)
                vtr.style.backgroundColor = '#FFFFC0';   /* CC alternate background color */
//             else if (vname.indexOf('(att') != -1)
//                vtr.style.backgroundColor = '#FFFFFF';   /* caucus attendee background color if convention */
          }
       }
       else {      /* error: set to previous value */
          if (ckset_s == '1')
             ckref.checked = false;
          else
             ckref.checked = true;
          alert(o.responseText);
       }
    },
    failure: function(o) {   /* timeout?: set to previous value */
       var ckref = eid('trckin_' + ckvid_s + 'i');
       if (ckset_s == '1')
          ckref.checked = false;
       else
          ckref.checked = true;
       alert('Record did not update.  Possibly a timeout occurred.');
    },
    timeout: 5000
}
function ckinchg(obj)
{
   var ckset_s = '';
   var ckdelg_s = '';
   var vn = obj.id;
   ckvid_s = vn.substr(7, vn.length - 8);   /* voter id */
   ckfld = vn.substr(0, 6);
   switch(ckfld) {
      case 'trckin':
        var delgfld = eid('trdelg_' + ckvid_s + 'i');
        if (obj.checked) {
           ckset_s = '1';
           if (((eid('tdname_' + ckvid_s + 'i').innerHTML).indexOf('(alt')) >= 0)   /* an alternate */
              delgfld.disabled = '';  /* allow selection as a delegate */
           if (((eid('tdname_' + ckvid_s + 'i').innerHTML).indexOf('(delg')) >= 0) {   /* a delegate */
              delgfld.disabled = '';   /* enable delegate-selection checkbox and set on */
              delgfld.checked = true;
              ckdelg_s = '1';
           }
        }
        else {
           ckset_s = '0';
           delgfld.disabled = 'disabled';
           delgfld.checked = false;
           ckdelg_s = '0';
        }
        break;
      case 'trdelg':
        if (obj.checked)
           ckdelg_s = '1';
        else
           ckdelg_s = '0';
        break;
   }
   try {   /* move focus/select back to name */
      eid('lastnamei').focus();
      eid('lastnamei').select();
   } catch(e) {}
   var randno = new Date().getTime();
   var httprqs = 'voter_update_proc.php?opt=convckin&voter_id=' + ckvid_s +
        '&setin=' + ckset_s + '&setdelg=' + ckdelg_s + '&__rand=' + randno;
   var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, ckinchg_cb);
   return(true);
}
/* ======================================================================= */
/*  enable check-in status fields, and delegate field if checked-in */
/*  also makes the Refresh button visible */
function enable_trckin()
{
   var tk = document.getElementsByName('trckin');
   var delg = document.getElementsByName('trdelg');
   for (var i = 0; i < tk.length; i++) {
      var tkele = tk[i];
      tkele.disabled = '';
      if (tkele.checked)
         delg[i].disabled = '';
   }
   try {
      eid('refreshi').style.display = '';
   } catch(e) {}
}
/* ======================================================================= */
/*  set vertical scrollbar on a <div> section if window height too small */
function div_scrollbar(div_id, div_height)
{
   var h = 0;
   if (window.innerHeight)
      h = window.innerHeight;
   else if (document.documentElement && document.documentElement.clientHeight)
      h = document.documentElement.clientHeight;
   else if (document.body.clientHeight)
      h = document.body.clientHeight;
   if (h < div_height)
   {
      try {
         eid(div_id).style.overflow = 'scroll';
      } catch(e) {}
   }
}
/* ======================================================================= */
/*  add pollsite to precinct field */
function pollsite(precinct, pselem)
{
   gl_pselem = pselem;
   var randno = new Date().getTime();
   var httprqs = 'precinct_pollsite_proc.php?precinct=' + encodeURIComponent(precinct) + '&__rand=' + randno;
   var co = YAHOO.util.Connect.asyncRequest('GET', httprqs, pollsite_cb);
}
var pollsite_cb = {
    success: function(o) {
       eid(gl_pselem).innerHTML = '<br><span style="font-weight:bold;font-size:75%;">' + o.responseText +
         '</span>';
    },
    failure: function(o) {
    },
    timeout: 10000
}
