var popup_dragging = false;
var popup_target;
var popup_mouseX;
var popup_mouseY;
var popup_mouseposX;
var popup_mouseposY;
var count1 = 0;
var count2 = 0;
var msgup = 1;
var glb_lenword = 0;
var glb_index = -1;
var glb_sel_disp = 24;
var glb_arrow = 0;
var glb_ifrmpx = 440;
var glb_c_header_bg = 'fff';
var glb_c_select_border = 'fff';
var doingedit = false;

var glb_rmd_adrbook;
var glb_rmd_date_id;
var glb_rmd_exit;
var glb_rmd_email;
var glb_rmd_app_id;
var glb_dateedit_mode = 0;
var glb_time_opt = '';
var glb_do_delete = '';
var max_contacts = 31;

function j_paid_customer(num) {
    max_contacts = num;
}

function ck_max_customer() {
    
  if (max_contacts == 0 ) {
    return(false);
  }
  var elSel = document.getElementById('selectX');
  if (elSel.length < max_contacts) {
    return(false);
  }
  return(true);
}

function getScrollWidth()
{
   var w = window.pageXOffset ||
           document.body.scrollLeft ||
           document.documentElement.scrollLeft;
           
   return w ? w : 0;
}

function getScrollHeight()
{
   var h = window.pageYOffset ||
           document.body.scrollTop ||
           document.documentElement.scrollTop;
           
   return h ? h : 0;
}

// ----- popup_mousepos --------------------------------------------------------

function popup_mousepos(e)
{
  var ie = navigator.appName == "Microsoft Internet Explorer";

  popup_mouseposX = ie ? window.event.clientX : e.clientX;
  popup_mouseposY = ie ? window.event.clientY : e.clientY;
}

// ----- Attach Events ---------------------------------------------------------

if (navigator.appName == "Microsoft Internet Explorer")
     document.attachEvent('onmousedown', popup_mousepos);
else document.addEventListener('mousedown', popup_mousepos, false);

if (navigator.appName == "Microsoft Internet Explorer")
     document.attachEvent('onmousemove', popup_mousemove);
else document.addEventListener('mousemove', popup_mousemove, false);

if (navigator.appName == "Microsoft Internet Explorer")
     document.attachEvent('onmouseup', popup_mouseup);
else document.addEventListener('mouseup', popup_mouseup, false);

function popup_mousedown(e)
{
  var ie = navigator.appName == "Microsoft Internet Explorer";

  if ( ie && window.event.button != 1) return;
  if (!ie && e.button            != 0) return;

  popup_dragging = true;
  popup_target   = this['target'];
  popup_mouseX   = ie ? window.event.clientX : e.clientX;
  popup_mouseY   = ie ? window.event.clientY : e.clientY;

  if (ie)
       popup_oldfunction      = document.onselectstart;
  else popup_oldfunction      = document.onmousedown;

  if (ie)
       document.onselectstart = new Function("return false;");
  else document.onmousedown   = new Function("return false;");
}

// ----- popup_mousemove -------------------------------------------------------

function popup_mousemove(e)
{
  if (!popup_dragging) return;

  var ie      = navigator.appName == "Microsoft Internet Explorer";
  var element = document.getElementById(popup_target);

  var mouseX = ie ? window.event.clientX : e.clientX;
  var mouseY = ie ? window.event.clientY : e.clientY;

  element.style.left = (element.offsetLeft+mouseX-popup_mouseX)+'px';
  element.style.top  = (element.offsetTop +mouseY-popup_mouseY)+'px';

  popup_mouseX = ie ? window.event.clientX : e.clientX;
  popup_mouseY = ie ? window.event.clientY : e.clientY;
}

// ----- popup_mouseup ---------------------------------------------------------

function popup_mouseup(e)
{
  if (!popup_dragging) return;
  popup_dragging = false;

  var ie      = navigator.appName == "Microsoft Internet Explorer";
  var element = document.getElementById(popup_target);

  if (ie)
       document.onselectstart = popup_oldfunction;
  else document.onmousedown   = popup_oldfunction;
}

// ----- popup_exit ------------------------------------------------------------

function popup_exit(e)
{
  var ie      = navigator.appName == "Microsoft Internet Explorer";
  var element = document.getElementById(popup_target);

  popup_mouseup(e);
  element.style.visibility = 'hidden';
  element.style.display    = 'none';
}


function popup_exit2(e) {
  var ie      = navigator.appName == "Microsoft Internet Explorer";
  var element = document.getElementById(e);


  popup_mouseup(e);
  element.style.visibility = 'hidden';
  element.style.display    = 'none';
  $('erroremail').style.visibility = "hidden";
  $('erroremail').style.display = "none";
  $('loginmsg').innerHTML = '';

  if (e == 'emailpopup') {
      $("emailsubject").value = '';
      $('emailbody').value = '';
  }

}

function advanceremind() {
  var vars = new Array();
  var elSel1 = document.getElementById('rmdselect_1');
  var elSel2 = document.getElementById('rmdselect_2');

  vars['emailto'] = $(glb_rmd_email).value;
  vars['appendtext'] = $(glb_rmd_app_id).value;
  vars['date_id'] = glb_rmd_date_id;
  vars['rmdselect_1'] = elSel1.options[elSel1.selectedIndex].value;  
  vars['rmdselect_2'] = elSel1.options[elSel2.selectedIndex].value;  

  srvpath = '/spiderfrock/' + glb_rmd_adrbook + '/ajaxreminddate';
  popup_exit2(glb_rmd_exit);

  ajaxCaller.postForPlainText(srvpath, vars, ReturnRemind)
}

function ReturnRemind(id_newstring) {
    //alert(id_newstring);
    info_array = id_newstring.split("\t");
    display_active_record_refresh();
}

function sendtestemail(email_id, comment_id) {
    person_id = $('person_id').value;
    if ($(email_id).value == '') {
        alert('You need to provide an email address');
        return;
    }
    alert('Test message sent to: ' + $(email_id).value + '\n\nYou should find the message in your Inbox.');

    var vars = new Array();
    var elSel1 = document.getElementById('rmdselect_1');
    var elSel2 = document.getElementById('rmdselect_2');

    vars['emailto'] = $(email_id).value;
    vars['appendtext'] = $(comment_id).value;
    vars['date_id'] = glb_rmd_date_id;
    vars['rmdselect_1'] = elSel1.options[elSel1.selectedIndex].value;  
    vars['rmdselect_2'] = elSel1.options[elSel2.selectedIndex].value;  

    srvpath = '/spiderfrock/' + glb_rmd_adrbook + '/ajaxsampleremind';

    ajaxCaller.postForPlainText(srvpath, vars, ReturnSample)
}

function ReturnSample(id_newstring) {
    //alert(id_newstring);
    info_array = id_newstring.split("\t");
}

function setreminder(adrbook, date_id, id, drag_id, div_id, sdate, sel1, sel2, id_sel1, id_sel2, id_exit, emailadr, email_id, monthdayyear, mdyid, apptext, app_id) {

    if (glb_dateedit_mode == 1){
        return;
    }
    glb_rmd_adrbook = adrbook;
    glb_rmd_date_id = date_id;
    glb_rmd_exit = id_exit;
    glb_rmd_email = email_id;
    glb_rmd_app_id = app_id;
    apptext = apptext.replace(/XXsXX/g, "'").replace(/XXdXX/g, '"').replace(/XXcrXX/g, "\r");
    $(email_id).value = emailadr;
    $(div_id).innerHTML = sdate;
    $(id_sel1).innerHTML = sel1;
    $(id_sel2).innerHTML = sel2;
    $(mdyid).innerHTML = monthdayyear;
    $(app_id).value = apptext;
    element      = document.getElementById(id);
    drag_element = document.getElementById(drag_id);

    element.style.position   = "absolute";
    element.style.display    = "block";

    element.style.left = (getScrollWidth()+popup_mouseposX-element.clientWidth /2-10)+'px';
    element.style.top  = (getScrollHeight() +popup_mouseposY-element.clientHeight/2+20)+'px';

    drag_element['target']   = id;
    drag_element.onmousedown = popup_mousedown;
    element.style.visibility = "visible";
}

function adjust_header(user_login_name, login_logout_text) {
    $('id_user_login_name').innerHTML = user_login_name;
    $('id_login_or_out').innerHTML = login_logout_text;
    if (login_logout_text == '') {
        $('id_security').value = 'admin';
    }
    else {
        $('id_security').value = user_login_name;
    }
}

function dologinorout(adrbook, id, drag_id) {
    state = $('id_login_or_out').innerHTML;
    if (state == 'login') {
        dologin(adrbook, id, drag_id);
    } else {
        dologout(adrbook);
    }
}

function dologin(adrbook, id, drag_id, do_delete) {

    glb_rmd_adrbook = adrbook;
    glb_rmd_exit = id;
    if (do_delete == 'delete') {
        glb_do_delete = 'delete';
    }else {
        glb_do_delete = '';
    }
    element      = document.getElementById(id);
    drag_element = document.getElementById(drag_id);

    element.style.position   = "absolute";
    element.style.display    = "block";

    element.style.left = (getScrollWidth()+(document.body.clientWidth -element.clientWidth )/2+ -10)+'px';
    element.style.top  = (150 +(element.clientHeight)/2 + -10)+'px';

    drag_element['target']   = id;
    drag_element.onmousedown = popup_mousedown;
    element.style.visibility = "visible";
    $('id_password').focus();
}

function rtnfalse() {
    return(false);
}


function dologin2(adrbook) {
    var vars = new Array();
    vars['password'] = $('id_password').value;
    vars['adrbook'] = adrbook;
    if ( glb_do_delete == 'delete'){
        vars['do_delete'] = 'delete';
    }
    vars['ajax'] = 'ajax';
    srvpath = '/spiderfrock/' + adrbook + '/login';

    ajaxCaller.postForPlainText(srvpath, vars, Return_Login)
}

function Return_Login(id_newstring) {
    //alert(id_newstring);
    info_array = id_newstring.split("\t");
    if (info_array[0] == 'Passed') {
        $('id_security').value = info_array[1];
        $('id_login_or_out').innerHTML = 'logout';
        adrbook = info_array[2]
        if ($('id_loginmode').value == 'view') {
            location.href = '/spiderfrock/' + info_array[2];
            return;
        }
        if (info_array[1] == 'admin') {
            $('id_user_login_name').innerHTML = 'Admin';
            if ($('id_loginnext').value == 'import') {
                importform(info_array[2], 'yes');
            }
            else if ($('id_loginnext').value == 'export') {
                exportform(info_array[2], 'yes');
            }
            else if ($('id_loginnext').value == 'reminders') {
                reminderform(info_array[2], 'yes');
            }
            else if ($('id_loginnext').value == 'passwords') {
                syspasswords(info_array[2], 'yes');
            }
            else if ($('id_loginnext').value == 'sysopts') {
                sysoptions(info_array[2], 'yes');
            }
            else if ($('id_loginnext').value == 'iotemplate') {
                iotemplate(info_array[2], 'yes');
            }

            else if ($('id_loginnext').value == 'edit') {
                Edit_Select_Record(info_array[2]);
            }
            else if ($('id_loginnext').value == 'delete') {
                Delete_Select_Record(info_array[2], 'yes');
            }
            else {
                popup_exit2('logindiv');
                //location.href = '/spiderfrock/' + info_array[2];
            }
        }
        else if (info_array[1] == 'edit') {
            $('id_user_login_name').innerHTML = 'Edit';
            if ($('id_loginnext').value == 'edit') {
                Edit_Select_Record(info_array[2]);
            }
            else if ($('id_loginnext').value == 'delete') {
                Delete_Select_Record(info_array[2], 'yes');
            }
            else {
                popup_exit2('logindiv');
                //location.href = '/spiderfrock/' + info_array[2];
            }
        }
        else if (info_array[1] == 'add') {
            $('id_user_login_name').innerHTML = 'Add';
            if ($('id_loginnext').value == 'add') {
                Add_New_Record(info_array[2]);
            }
        }
        else {
                popup_exit2('logindiv');
                location.href = '/spiderfrock/' + info_array[2];
        }
        $('logindiv').style.visibility = "hidden";
        $('logindiv').style.display = "none";
    } else
    {
        $('loginmsg').innerHTML = info_array[1];
        $('erroremail').style.visibility = "visible";
        $('erroremail').style.display = "block";
    }
}

function loginemailpass(adrbook) {
    var vars = new Array();
    vars['adrbook'] = adrbook;
    vars['ajax'] = 'ajaxemail';
    srvpath = '/spiderfrock/' + adrbook + '/login';
    ajaxCaller.postForPlainText(srvpath, vars, Return_Login)
}

function dologout(adrbook) {
    //location.href = '/spiderfrock/' + adrbook + '/logout';
    var vars = new Array();
    vars['adrbook'] = adrbook;
    srvpath = '/spiderfrock/' + adrbook + '/logout';
    ajaxCaller.postForPlainText(srvpath, vars, Return_Logout)
}
function Return_Logout(id_newstring) {
    //alert(id_newstring);
    info_array = id_newstring.split("\t");
    $('id_user_login_name').innerHTML = '';
    $('id_login_or_out').innerHTML = 'login';
    $('id_security').value = '';
    $('id_loginnext').value = '';
    if (info_array[0] == 'nologin') {
        display_active_record_refresh();
    } else {
        path = '/spiderfrock/' + info_array[1] + '/';
        //location.href = '/spiderfrock/' + info_array[1] + '/';
        location.href = path;
    }
}

//document.onkeyup = checkKeycode;

function clearcheck() {
    doingedit = false;
    return(true);
}

window.onresize = function () {
resizetheselect();
 }

function onloadcalls(c_header_bg, c_select_border, c_select_interior, c_menu_op, active_color, person_id, do_welcome, got_an_id) {
    var elSel = document.getElementById('selectX');
    theIframe= $('ifrm');
    resizetheselect();
    theIframe.style.height =  glb_ifrmpx + "px";
    //startList();
    assigncolors(c_header_bg, c_select_border, c_select_interior, c_menu_op, active_color);

    if (do_welcome == 'welcome') {
        return;
    }
    if (person_id == '') {
        person_id = -1;
    }
    if (got_an_id != '') {
        // find person id
        person_id = locate_person_index(got_an_id);
        
    }
    display_active_record(person_id)

    if ((person_id <= elSel.length) && (person_id > 0)){
        elSel.options[person_id].selected = true;
        nameselected(document.thisform.adrlist);
    }
    if (dofilter == 'yes') {
        bld_array();
    }
}

function bld_array(){
    var  elSel = $('selectX');
    for (i = 0; i < elSel.length; i++) {
        thevalue = elSel.options[i].value;
        info_array = thevalue.split("\t");
        lastfirst = info_array[0].replace(', ','\t');
        person_id = info_array[1];
        fa[i] = lastfirst + '\t' + person_id + '\t';
    }
    fa.length= elSel.length;
}

function assigncolors(c_header_bg, c_select_border, c_select_interior, c_menu_op, active_color) {
    glb_c_header_bg = c_header_bg;
    glb_c_select_border = c_select_border;
  changecss('.box', 'background', c_header_bg);
  changecss('div.remind_popup div.board_header', 'background', c_header_bg);
  changecss('.email_adr a:link', 'color', c_header_bg);
  changecss('.url_adr a:link', 'color', c_header_bg);
  changecss('.url_adr a:visited', 'color', c_header_bg);
  changecss('.url_adr a:active', 'color', c_header_bg);
  changecss('.map_adr a:link', 'color', c_header_bg);
  changecss('.map_adr a:visited', 'color', c_header_bg);
  changecss('.map_adr a:active', 'color', c_header_bg);
  changecss('.savelink', 'color', c_header_bg);
  changecss('.urlemail a:link', 'color', c_header_bg);
  changecss('.urlemail a:visited', 'color', c_header_bg);
  changecss('.urlemail a:active', 'color', c_header_bg);
  changecss('.editsubmit', 'background-color', c_header_bg);
  changecss('.editsubmit', 'border-color', c_select_border);
  changecss('.editdelete', 'background-color', c_header_bg);
  changecss('.editdelete', 'border-color', c_select_border);
  changecss('.boxsel', 'background', c_select_border);
  changecss('.nameselect', 'background', c_select_interior);
  changecss('.nameinput', 'background', c_select_interior);
  changecss('.inputajax', 'background', c_select_interior);
  changecss('.chromestyle ul li a', 'color', c_menu_op);
  changecss('.dropmenudiv a', 'color', c_menu_op);
  changecss('.dropmenudiv a:hover', 'background-color', c_select_interior);
  changecss('.boxtop', 'background', 'url(/spiderfrock/bookimages/ne_' + active_color + '.gif) no-repeat top right');
  changecss('.boxtop div', 'background', 'url(/spiderfrock/bookimages/nw_' + active_color + '.gif) no-repeat top left');
  changecss('.boxbottom', 'background', 'url(/spiderfrock/bookimages/se_' + active_color + '.gif) no-repeat bottom right');
  changecss('.boxbottom div', 'background', 'url(/spiderfrock/bookimages/sw_' + active_color + '.gif) no-repeat bottom left');
  changecss('.boxtopsel', 'background', 'url(/spiderfrock/bookimages/nesel_' + active_color + '.gif) no-repeat top right');
  changecss('.boxtopsel div', 'background', 'url(/spiderfrock/bookimages/nwsel_' + active_color + '.gif) no-repeat top left');
  changecss('.boxbottomsel', 'background', 'url(/spiderfrock/bookimages/sesel_' + active_color + '.gif) no-repeat bottom right');
  changecss('.boxbottomsel div', 'background', 'url(/spiderfrock/bookimages/swsel_' + active_color + '.gif) no-repeat bottom left');

}

function buttonover(thebutton){
  changecss('.' + thebutton, 'background-color', glb_c_select_border);
  changecss('.' + thebutton, 'border-color', glb_c_header_bg);
  changecss('.' + thebutton, 'color', '#333');
}

function buttonout(thebutton){
  changecss('.' + thebutton, 'background-color', glb_c_header_bg);
  changecss('.' + thebutton, 'border-color', glb_c_select_border);
  changecss('.' + thebutton, 'color', '#FFF');
}


function startList() {
	if (document.all&&document.getElementById) {
		navRoot = document.getElementById("nav");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}

function resizetheselect() {
     appV =  navigator.appVersion;
     //alert("appName = " + navigator.appName + '  version = ' + navigator.appVersion);
     height = getWinHeight();
     if (appV.match('Chrome')) {
         myheight = parseInt((height - 140) / 17);
         setSelectSize(myheight);
         glb_ifrmpx = height - 160;
         theIframe= $('ifrm');
         //alert('glb_ifrmpx = ' + glb_ifrmpx);
         //alert('adminop  = ' + $('adminop').style.visibility );
         if ($('adminop').style.visibility == "visible") {
             theIframe.style.height =  glb_ifrmpx + "px";
         }
     //alert('found chrome');
     }
     else if (navigator.appName == 'Netscape') {
         myheight = parseInt((height - 140) / 16);
         setSelectSize(myheight);
         glb_ifrmpx = height - 160;
         if ($('adminop').style.visibility == "visible") {
             theIframe.style.height =  glb_ifrmpx + "px";
             }
     }
     //else if (navigator.appName == 'Microsoft Internet Explorer') {
     else {
         myheight = parseInt((height - 170) / 16);
         setSelectSize(myheight);
         glb_ifrmpx = height - 190;
         if ($('adminop').style.visibility == "visible") {
             theIframe.style.height =  glb_ifrmpx + "px";
             }
     }
     glb_sel_disp = myheight;

}

    function getWinHeight () {
        this.height = 0;
        if (window.innerHeight) 
            this.height = window.innerHeight - 18;
        else if (document.documentElement && document.documentElement.clientHeight) 
            this.height = document.documentElement.clientHeight;
        else if (document.body && document.body.clientHeight) 
            this.height = document.body.clientHeight;
        return this.height;
    }


function checkKeycode(e) {
var keycode;
    alert('CheckEnter 1xx');
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;

if ((keycode == 38) || (keycode == 40)) {
    arrowkeys(keycode);
    }
}

function checkEnter(e, op, fld_id, fld_id_0, fld_text){ //e is event object
var characterCode 

if(e && e.which){ //if which property of event object is supported (NN4)
e = e
characterCode = e.which //character code is contained in NN4's which property
}
else{
e = event
characterCode = e.keyCode //character code is contained in IE's keyCode property
}

if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
  if (op == 'phone') {
    ajaxsavephone(fld_id, fld_id_0, fld_text);
  }
  else if (op == 'email') {
    ajaxsaveemail(fld_id, fld_id_0, fld_text);
  }
  else if (op == 'url') {
    ajaxsaveurl(fld_id, fld_id_0, fld_text);
  }
  else if (op == 'date') {
    ajaxsavedate(fld_id, fld_id_0, fld_text);
  }
  else if (op == 'custom') {
    ajaxsavecustom(fld_id, fld_id_0, fld_text);
  }
  else if (op == 'login') {
    dologin2(fld_text);
  }
return false
}
else{
return true
}

}

var ajaxCaller = {

  shouldDebug: false,
  shouldEscapeVars: false,
  shouldMakeHeaderMap: true,

  calls : new Array(),
  pendingResponseCount : 0,

   /**************************************************************************
      PUBLIC METHODS
   *************************************************************************/

  getXML: function(url, callbackFunction) {
    this.get(url, null, callbackFunction, true, null);
  },

  getPlainText: function(url, callbackFunction) {
    this.get(url, null, callbackFunction, false, null);
  },

  postForPlainText: function(url, vars, callbackFunction) {
    this.postVars(url, vars, null, callbackFunction, false,
                    null, "POST", null, null, null);
  },

  postForXML: function(url, vars, callbackFunction) {
    this.postVars(url, vars, null, callbackFunction, true,
                    null, "POST", null, null, null);
  },

  get: function(url, urlVars, callbackFunction, expectingXML, callingContext) {
    this._callServer(url, urlVars, callbackFunction, expectingXML,
                    callingContext, "GET", null, null, null);
  },

  postVars:
    function(url, bodyVars, optionalURLVars, callbackFunction, expectingXML,
             callingContext) {
      this._callServer(url, optionalURLVars, callbackFunction, expectingXML,
                      callingContext, "POST", bodyVars, null, null);
  },

  postBody:
    function(url, optionalURLVars, callbackFunction, expectingXML,
             callingContext, bodyType, body) {
      this._callServer(url, optionalURLVars, callbackFunction, expectingXML,
                      callingContext, "POST", null, bodyType, body);
  },

  putBody:
    function(url, optionalURLVars, callbackFunction, expectingXML,
             callingContext, bodyType, body) {
      this._callServer(url, optionalURLVars, callbackFunction, expectingXML,
                      callingContext, "PUT", null, bodyType, body);
  },

  options:
    function(url, optionalURLVars, callbackFunction, expectingXML,
             callingContext, bodyType, body) {
      this._callServer(url, optionalURLVars, callbackFunction, expectingXML,
                      callingContext, "OPTIONS", null, bodyType, body);
  },

  trace:
    function(url, optionalURLVars, callbackFunction, expectingXML,
             callingContext, bodyType, body) {
      this._callServer(url, optionalURLVars, callbackFunction, expectingXML,
                      callingContext, "TRACE", null, bodyType, body);
  },

  deleteIt: function(url, urlVars, callbackFunction,
                     expectingXML, callingContext) {
    this._callServer(url, urlVars, callbackFunction, expectingXML,
                    callingContext, "DELETE", null, null, null);
  },

  head: function(url, urlVars, callbackFunction, expectingXML, callingContext)
  {
    this._callServer(url, urlVars, callbackFunction, expectingXML,
                    callingContext, "HEAD", null, null, null);
  },

  /**************************************************************************
     PRIVATE METHODS
  *************************************************************************/

  _callServer: function(url, urlVars, callbackFunction, expectingXML,
                       callingContext, requestMethod, bodyVars,
                       explicitBodyType, explicitBody) {

    if (urlVars==null) {
      urlVars = new Array();
    }

    this._debug("_callServer() called. About to request URL\n"
                + "call key: [" + this.calls.length + "]\n"
                + "url: [" + url + "]\n"
                + "callback function: [" + callbackFunction + "]\n"
                + "treat response as xml?: [" + expectingXML + "]\n"
                + "Request method?: [" + requestMethod + "]\n"
                + "calling context: [" + callingContext + "]\n"
                + "explicit body type: [" + explicitBodyType + "]\n"
                + "explicit body: [" + explicitBody + "]\n"
                + "urlVars: [" + this._describe(urlVars) + "]\n"
                + "bodyVars: [" + this._describe(bodyVars) + "]"
              );


    var xReq = this._createXMLHttpRequest();
    xReq.onreadystatechange = function() {
      ajaxCaller._onResponseStateChange(call);
    }

    var call = {xReq: xReq,
                callbackFunction: callbackFunction,
                expectingXML: expectingXML,
                callingContext: callingContext,
                url: url};

    if (urlVars!=null) {
      var urlVarsString = this._createHTTPVarSpec(urlVars);
      if (urlVarsString.length > 0) { // TODO check if appending with & instead
        url += "?" + urlVarsString;
      }
    }

    xReq.open(requestMethod, url, true);

    if (   requestMethod=="GET"
        || requestMethod=="HEAD"
        || requestMethod=="DELETE") {
      this._debug("Body-less request to URL " + url);
      xReq.send(null);
      return;
    }

    if (   requestMethod=="POST"
        || requestMethod=="PUT"
        || requestMethod=="OPTIONS"
        || requestMethod=="TRACE") {
      bodyType = null;
      body = null;
      if (explicitBodyType==null) { // It's a form
        bodyType = 'application/x-www-form-urlencoded; charset=UTF-8';
        body = this._createHTTPVarSpec(bodyVars);
      } else {
        bodyType = explicitBodyType;
        body = explicitBody;
      }
      this._debug("Content-Type: [" + bodyType + "]\nBody: [" + body + "].");
      xReq.setRequestHeader('Content-Type',  bodyType);
      xReq.send(body);
      return;
    }

    this._debug("ERROR: Unknown Request Method: " + requestMethod);

  },

  // The callback of xmlHttpRequest is a dynamically-generated function which
  // immediately calls this function.
  _onResponseStateChange: function(call) {

    xReq = call.xReq;

    if (xReq.readyState < 4) { //Still waiting
      return;
    }

    if (xReq.readyState == 4) { //Transmit to actual callback
      this._debug("Call " + ajaxCaller._describe(call)
                + " with context [" + call.callingContext+"]"
                + " to " + call.url + " has returned.");
      callbackFunction = call.callbackFunction;
      if (!callbackFunction) { // Maybe still loading, e.g. in another JS file
        setTimeout(function() {
          _onResponseStateChange(call);
        }, 100);
      }
      var content = call.expectingXML ? xReq.responseXML : xReq.responseText;
      responseHeaders = xReq.getAllResponseHeaders();
      headersForCaller = this.shouldMakeHeaderMap ?
        this._createHeaderMap(responseHeaders) : responseHeaders;
      callbackFunction(content, headersForCaller, call.callingContext);
    }

    call = null; // Technically the responsibility of GC
    this.pendingResponseCount--;

  },

  // Browser-agnostic factory function
  _createXMLHttpRequest: function() {
      try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
      try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
      try { return new XMLHttpRequest(); } catch(e) {}
      alert("XMLHttpRequest not supported");
      return null;
    },

  _createHTTPVarSpec: function(vars) {
      var varsString = "";
      for( key in vars ) {
        var value = vars[key];
        if (this.shouldEscapeVars) {
          escapePlusRE =  new RegExp("\\\+");
          value = value.replace(escapePlusRE, "%2B");
        }
        varsString += '&' + key + '=' + value;
      }
      if (varsString.length > 0) {
        varsString = varsString.substring(1); // chomp initial '&'
      }
      this._debug("Built var String: " + varsString)
      return varsString;
   },

  /* Creates associative array from header type to header */
  _createHeaderMap: function(headersText) {
    extractedHeaders = headersText.split("\n");
    delete extractedHeaders[extractedHeaders.length]; // Del blank line at end
    headerMap = new Array();
    for (i=0; i<extractedHeaders.length-2; i++) {
      head = extractedHeaders[i];
      fieldNameEnding = head.indexOf(":");
      field = head.substring(0, fieldNameEnding);
      value = head.substring(fieldNameEnding + 2, head.length);
      value = value.replace(/\s$/, "");
      headerMap[field] = value;
    }
    return headerMap;
  },

  _describe: function(obj) {
    return document.util ? 
      util.describe(obj) : "Include util.js to describe " + obj;
  },

  _debug: function(message) {
      if (this.shouldDebug) {
        alert("AjaxJS Message:\n\n" + message);
      }
  },

  _error: function(message) {
      if (this.shouldDebug) {
        alert("AjaxJS ERROR:\n\n" + message);
      }
  }

};

function $(id) { return document.getElementById(id); }

function setSelectSize(num)
{
  $('selectX').size = num;
}

function insertOptionBefore(num)
{
  var elSel = document.getElementById('selectX');
  if (elSel.selectedIndex >= 0) {
    var elOptNew = document.createElement('option');
    elOptNew.text = 'Insert' + num;
    elOptNew.value = 'Insert' + num;
    var elOptOld = elSel.options[elSel.selectedIndex];  
    try {
      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew, elSel.selectedIndex); // IE only
    }
  }
}

function removeOptionSelected()
{
  if (dofilter == 'yes') {
      filterlist('');
  }

  var elSel = document.getElementById('selectX');
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].selected) {
      elSel.remove(i);
      break;
    }
  }
    if (dofilter == 'yes') {
        bld_array();
    }
}

function appendOptionLast(num)
{
  var elOptNew = document.createElement('option');
  elOptNew.text = 'Appending, First_Name' + num;
  elOptNew.value = 'append' + num;
  var elSel = document.getElementById('selectX');

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
}

function removeOptionLast()
{
  var elSel = document.getElementById('selectX');
  if (elSel.length > 0)
  {
    elSel.remove(elSel.length - 1);
  }
}

function setSelectedTextRange(elm, selectionStart, selectionEnd) {
    if (elm.setSelectionRange) {
        elm.focus();
        elm.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (elm.createTextRange) {
        var range = elm.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

function setCaretToEnd (elm) {
    setSelectedTextRange(elm, elm.value.length, elm.value.length);
}
function setCaretToStart (elm) {
    setSelectedTextRange(elm, 0, 0);
}
function setCaretToPos (elm, pos) {
    setSelectedTextRange(elm, pos, pos);
}

function insertlocation(cnt, itemlist) {
    alert("value = " + cnt);
    itemlist.options[cnt].selected = true;
}

function ClearText(obj) {
    if (msgup == 1 ) {
        msgup = 0;
        obj.value="";
    }
    changecss('.nameinput', 'text-align', 'left')
    changecss('.nameinput', 'color', '#333333')
    changecss('.nameinput', 'font-family', 'Arial, Serif')
}
function display_active_record_refresh() {
   // Force a refresh display
   doingedit = false;
   i = glb_index;
   // glb_index = -1;
   if (i == -1) {
        i = 0;
   }
   display_active_record(i)
}

function locate_person_index(find_id) {
  var  elSel = $('selectX');
  var i;
  var rtn_index = 0;
  for (i = 0; i < elSel.length; i++) {
    thevalue = elSel.options[i].value;
    info_array = thevalue.split("\t");

    person_id = info_array[1];
    if (person_id == find_id) {
        rtn_index = i;
        break
    }
  }
  return(i)
}

function display_active_record(index) {
    //alert("display glb_index = " + glb_index + "  index parameter = " + index);
    elSel = $('selectX');
    if (elSel.length == 0) {
        return;
    }
    if (index > elSel.length) {
        index = 1;
    }
    var vars = new Array();
    //alert("display_active record index = " + index + "  glb_indes = " + glb_index + '  glb_arrow =  ' + glb_arrow);

    if (index == glb_index)  {
        if (glb_arrow == 1) {
            glb_arrow = 0;
            return;
        }
        else {
           glb_arrow = 1;
        }
    }
    glb_arrow = 0;
    glb_index = index;

    $('id_midsection').className="cl_midempty";
    elSel = $('selectX');

    thename = elSel.options[index].value;  
    info_array = thename.split("\t");

    vars['person_id'] = info_array[1];
    vars['person_index'] = index;
    adrbook = document.thisform.adrbook.value;

    srvpath = '/spiderfrock/' + adrbook + '/ajaxgetperson';

    ajaxCaller.postForPlainText(srvpath, vars, Return_display_active_record)
}

// This is the return routine from an ajax display of a record
//
// See ajax file for field return order
//
function Return_display_active_record(id_newstring) {

    Show_Middle_Div('viewrecord');
    $("viewrecord").innerHTML = id_newstring;
    //eval($("id_msg_day").innerHTML);

}

function nsedit(adrbook) {
    // cold manage dblclick

t=setTimeout("Edit_Select_Record(adrbook)",100);
//Edit_Select_Record(adrbook);
    return;
}

function nameselected(obj) {
    if (doingedit) {
        rtn = confirm('Are you sure you want to stop editing this contact? Unsaved changes will be lost.');
        if (rtn == false)
            return;
    }
    doingedit = false;
    thename = obj.options[obj.selectedIndex].value;  
    info_array = thename.split("\t");

    ClearText(document.thisform.nameinput);
    document.thisform.nameinput.value = info_array[0];
    document.thisform.nameinput.select();

    // Call to display the  name
    display_active_record(obj.selectedIndex);
}

function arrowkeys(direction) {

     elSel = $('selectX');
     index = elSel.selectedIndex;
      if (direction == 40) {
         if ((index + 1) < elSel.length) {
            index = index + 1;
         }
      }
      else {
         if (index > 0 ) {
            index = index - 1;
         }
      }
      elSel.selectedIndex = index;
      //elSel.options[index].selected = true;
      nameselected(elSel);
      glb_index = index;
      glb_arrow = 1;
}
function filterlist(value) {
    //alert('FilterList value = ' + value);
    var elSel = $('selectX');
    var Oldvalue = 'None';
    theindex = elSel.selectedIndex;
    if (theindex >= 0) {
    Oldvalue = elSel.options[elSel.selectedIndex].value;  
    }
    elSel.length = 0;
    for (i = 0; i < fa.length; i++) {
        MYre=new RegExp(value, "i");
        if (fa[i].match(MYre)) {
            info_array = fa[i].split("\t");
            //alert('array length = ' + info_array.length);
            //alert('a[0] = ' + info_array[0] + ' a[1] = ' + info_array[1] + ' a[2] = ' + info_array[2]);
            var elOptNew = document.createElement('option');
            if (info_array.length == 4 ) {
            elOptNew.text = info_array[0] + ', ' + info_array[1];
            elOptNew.value = info_array[0] + ', ' + info_array[1] + '\t' + info_array[2];
            } else {
            elOptNew.text = info_array[0];
            elOptNew.value = info_array[0] + '\t' + info_array[1];
            }
            //helpit = elOptNew.value;
            //helpit = helpit.replace('\t', 'X');
            //helpit = helpit.replace('\t', 'X');
            //alert('helpit value = ' + helpit);
             try {
                elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
              }
              catch(ex) {
                elSel.add(elOptNew); // IE only
              }
        }
    }

    // now if we can find the old value in the select list, mark it as selected
     if (Oldvalue != 'None') {
     for (i = 0; i < elSel.length; i++) {
        if (elSel.options[i].value == Oldvalue) {
            elSel.selectedIndex = i;
            break;
        }
     }
     }

    // remove everything from the select list
}

function searchfield(obj) {
    value = obj.value;
    if (value ==  '-Type Name Here-') {
        // There might be a key entry error, skip any processing
        return;
    }
    if (value.substring(1,17) == '-Type Name Here-'){
        c = value.substr(0,1);
        ClearText(document.thisform.nameinput);
        obj.value= c;
        value = c;
    }
    if (value.substring(0,16) == '-Type Name Here-'){
        c = value.substr(16,17);
        ClearText(document.thisform.nameinput);
        obj.value= c;
        value = c;
    }
    if (dofilter == 'yes') {
        filterlist(value);
        return;
    }

    // Get the length of the typed text
    sglb_index = 0;
    lenword = value.length;
    if (lenword == 1){
        glb_lenword = 0;
        sglb_index = glb_index;
        glb_index = 0;
    }
    if (lenword == glb_lenword) {
        return;
    }

    // number of entries in the select;
    elSel = $('selectX');

    // Should we search up or down?
    if (lenword > glb_lenword){
        // Go down from our current select index
         for (i = glb_index; i < elSel.length; i++) {
            if (elSel.options[i].value.substr(0,lenword).toLowerCase() == value.toLowerCase()) {
                max_sel_opt = i;
                if (sglb_index > i) {
                    if (i >= 3) {
                        max_sel_opt = i - 2;
                    }
                }
                else {
                    if (glb_sel_disp > 3) {
                        max_sel_opt = i + glb_sel_disp -3;
                        if (max_sel_opt > elSel.length) {
                            //max_sel_opt = max_sel_opt - (max_sel_opt - elSel.length );
                            max_sel_opt = elSel.length - 1;
                        }
                    }
                }
                //alert("max = " + max_sel_opt + "   i = " + i);
                elSel.options[max_sel_opt].selected = true;
                elSel.options[i].selected = true;
                glb_index = i;
                display_active_record(glb_index )
                break;
            }
         }
    }else{
        // Go Up
         for (i = glb_index; i > -1; i--) {
             //alert('In loop --- ' + elSel.options[i].value.substr(0,lenword).toLowerCase() );
            if (elSel.options[i].value.substr(0,lenword).toLowerCase() < value.toLowerCase()) {
                i++;

                max_sel_opt = i;
                if (glb_sel_disp > 3) {
                    if (i >= 3) {
                    max_sel_opt = i - 2;
                    }
                }
                elSel.options[max_sel_opt].selected = true;


                elSel.options[i].selected = true;
                glb_index = i;
                display_active_record(glb_index )
                break;
            }
         }
         if (i == -1 ){
             // The top was reached without finding a match
            elSel.options[0].selected = true;
            glb_index = 0;
            display_active_record(glb_index )
         }
    }
    glb_lenword = lenword;
}

function changecss(theClass,element,value) {
 var cssRules;
 if (document.all) {
  cssRules = 'rules';
 }
 else if (document.getElementById) {
  cssRules = 'cssRules';
 }
 var added = false;
 for (var S = 0; S < document.styleSheets.length; S++){
  for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
   if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
    if(document.styleSheets[S][cssRules][R].style[element]){
    document.styleSheets[S][cssRules][R].style[element] = value;
    added=true;
    break;
    }
   }
  }

  if(!added){
  if(document.styleSheets[S].insertRule){
          document.styleSheets[S].insertRule(theClass+' { '+element+': '+value+'; }',document.styleSheets[S][cssRules].length);
        } else if (document.styleSheets[S].addRule) {
            document.styleSheets[S].addRule(theClass,element+': '+value+';');
        }
  }
 }
}
function Show_Middle_Div(activediv) {
  $('viewrecord').style.visibility = "hidden";
  $('viewrecord').style.display    = "none";
  $('addnewrecord').style.visibility = "hidden";
  $('addnewrecord').style.display    = "none";
  $('adminop').style.visibility = "hidden";
  $('adminop').style.display    = "none";
  $(activediv).style.visibility = "visible";
  $(activediv).style.display    = "block";
}

function Edit_Select_Record(adrbook) {
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit')) {
        if (checkedit() == false) {
            return;
        }
        doingedit = true;
        var obj = document.getElementById('selectX');
        if (obj.selectedIndex == -1) {
            obj.selectedIndex = 0;
        }
        thename = obj.options[obj.selectedIndex].value;  
        info_array = thename.split("\t");

        Show_Middle_Div('adminop');
        // info_array[1] contains the person id for database access
        srvpath = '/spiderfrock/' + adrbook + '/editrecord/' + info_array[1];
        theIframe.style.height =  glb_ifrmpx + "px";
        document.getElementById('ifrm').src = srvpath;
    }
    else {
        $('id_loginnext').value = 'edit';
        dologin(adrbook,'logindiv','login_drag');
    }

}

function Delete_Select_Record(adrbook, deleteprompt) {
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit')) {
        var obj = document.getElementById('selectX');
        var thename = obj.options[obj.selectedIndex].value;  
        var info_array = thename.split("\t");

        if (deleteprompt == 'yes') {
           var r=confirm("Delete   " + info_array[0] + " ?");
           if (r!=true)
           {
            return;
           }
        }


        removeOptionSelected();
        i = glb_index;
        var elSel = document.getElementById('selectX');
        $('recordcnt').innerHTML = 'Contacts ('+ elSel.length + ')';
        if (i > elSel.length -1) {
            i = elSel.length -1;
        }
        display_active_record(i)
        elSel.options[i].selected = true;
        nameselected(document.thisform.adrlist);

        //alert('Delete person id = ' + info_array[1] + 'X');
        // info_array[1] holds Person_id
        srvpath = '/spiderfrock/' + adrbook + '/ajaxdelete/' + info_array[1];
        ajaxCaller.getPlainText(srvpath, ReturnDelete)
    }
    else {
        $('id_loginnext').value = 'delete';
        dologin(adrbook,'logindiv','login_drag', 'delete');
    }
}

function ReturnDelete(id_newstring) {
// Do Nothing
}

function welcome_splash(adrbook ) {
    Show_Middle_Div('adminop');
    srvpath = '/spiderfrock/' + adrbook + '/splashwelcome/';
    theIframe.style.height =  glb_ifrmpx + "px";
    document.getElementById('ifrm').src = srvpath;
}


function Add_New_Record(adrbook ) {
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit') || (s == 'add')) {
        if (checkedit() == false) {
            return;
        }

        doingedit = true;
        Show_Middle_Div('adminop');
        srvpath = '/spiderfrock/' + adrbook + '/addrecord/';
        theIframe.style.height =  glb_ifrmpx + "px";
        document.getElementById('ifrm').src = srvpath;
    }
    else {
        $('id_loginnext').value = 'add';
        dologin(adrbook,'logindiv','login_drag');
    }
}


function show_first_name() {
  var elSel = document.getElementById('selectX');
  elSel.options[0].selected = true;
}

function add_to_list2(newname, theop){
    alert('Made it to add_to_list2()');
}

function add_to_list(newname, theop, dorefresh){
  if (dofilter == 'yes') {
      filterlist('');
   }
  var elSel = document.getElementById('selectX');
  doingedit = false;

  slen =  elSel.length;

  var theinsertindex = -1;
  for (i = 0; i < slen; i++){
    if (newname.toLowerCase() < elSel.options[i].value.toLowerCase()) {
        break;
    }
  }

  if ((i < slen) || (i == 0)) {
    var elOptNew = document.createElement('option');
    elOptNew.text = newname
    elOptNew.value = theop
    if (slen > 0) {
    var elOptOld = elSel.options[i];  
    }
    else {
        var elOptOld = elSel.options[0];  
    }
    try {
      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew, i); // IE only
    }
  }
  else {
     // This is an append to the end
     var elOptNew = document.createElement('option');
     elOptNew.text = newname
     elOptNew.value = theop
     try {
        elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
      }
      catch(ex) {
        elSel.add(elOptNew); // IE only
      }
  }
  elSel.options[i].selected = true;
  obj = document.thisform.adrlist;

  // Change the record count
  $('recordcnt').innerHTML = 'Contacts (' + (slen + 1) + ')'; 
  if (dorefresh == 'yes') {
      nameselected(obj);
  }
    // build the array if doing filter
    if (dofilter == 'yes') {
        bld_array();
    }
}

function checkedit() {
    if (doingedit) {
        return(confirm('Are you sure you want to stop editing this contact? Unsaved changes will be lost.'));
    }
    return(true);
}

function tips(adrbook) {
        if (checkedit() == false) {
            return;
        }
        doingedit = false;
        Show_Middle_Div('adminop');
        srvpath = '/spiderfrock/' + adrbook + '/tips';
        document.getElementById('ifrm').src = srvpath;
}

function syspasswords(adrbook) {
    s =  $('id_security').value;
    if (s == 'admin') {
        if (checkedit() == false) {
            return;
        }
        doingedit = false;
        Show_Middle_Div('adminop');
        srvpath = '/spiderfrock/' + adrbook + '/passwords';
        document.getElementById('ifrm').src = srvpath;
    } else {
        $('id_loginnext').value = 'passwords';
        dologin(adrbook,'logindiv','login_drag');
    }
}

function importform(adrbook) {
    s =  $('id_security').value;
    if (s == 'admin') {
        if (checkedit() == false) {
            return;
        }
        doingedit = false;
        Show_Middle_Div('adminop');
        srvpath = '/spiderfrock/' + adrbook + '/importdataform';
        document.getElementById('ifrm').src = srvpath;
    }
    else {
        $('id_loginnext').value = 'import';
        dologin(adrbook,'logindiv','login_drag');
    }
}

function exportform(adrbook) {
    s =  $('id_security').value;
    if (s == 'admin') {
        if (checkedit() == false) {
            return;
        }
        doingedit = false;
        Show_Middle_Div('adminop');
        srvpath = '/spiderfrock/' + adrbook + '/exportdataform';
        document.getElementById('ifrm').src = srvpath;
    }
    else {
        $('id_loginnext').value = 'import';
        dologin(adrbook,'logindiv','login_drag');
    }
}

function reminderform(adrbook) {
    s =  $('id_security').value;
    if (s == 'admin') {
        if (checkedit() == false) {
            return;
        }
        doingedit = false;
        Show_Middle_Div('adminop');
        srvpath = '/spiderfrock/' + adrbook + '/reminderdataform';
        document.getElementById('ifrm').src = srvpath;
    }
    else {
        $('id_loginnext').value = 'reminders';
        dologin(adrbook,'logindiv','login_drag');
    }
}

function sysoptions(adrbook) {
    s =  $('id_security').value;
    if (s == 'admin') { 
        if (checkedit() == false) {
            return;
        }
        doingedit = false;
        Show_Middle_Div('adminop');
        srvpath = '/spiderfrock/' + adrbook + '/sysoptions';
        document.getElementById('ifrm').src = srvpath;
    } else {
        $('id_loginnext').value = 'sysopts';
        dologin(adrbook,'logindiv','login_drag');
    }
}

function iotemplate(adrbook) {
    s =  $('id_security').value;
    if (s == 'admin') {
        if (checkedit() == false) {
            return;
        }
        doingedit = false;
        Show_Middle_Div('adminop');
        srvpath = '/spiderfrock/' + adrbook + '/iotemplate';
        document.getElementById('ifrm').src = srvpath;
    } else {
        $('id_loginnext').value = 'iotemplate';
        dologin(adrbook,'logindiv','login_drag');
    }
}

function Returnimportform(id_newstring) {

    info_array = id_newstring.split("\t");

    if (info_array[0].substring(0,1).toLowerCase() == 's') {
    }
    else {
        alert('Returnimportform got an error');
    }
    Show_Middle_Div('adminop');
    $('id_midsection').className="admin_op";
    $("rawdata").innerHTML = info_array[1];
}

function Returnexportform(id_newstring) {

    info_array = id_newstring.split("\t");

    if (info_array[0].substring(0,1).toLowerCase() == 's') {
    }
    else {
        alert('Returnexportform got an error');
    }
    Show_Middle_Div('adminop');
    $('id_midsection').className="admin_op";
    $("rawdata").innerHTML = info_array[1];
}

function Add_New_Record2() {
    Show_Middle_Div('addnewrecord');
    $('id_midsection').className="cl_midempty";
}

function addnewperson(adrbook) {
  var vars = new Array();

  $('id_midsection').className="cl_midempty";
  lastname = $('add_lastname').value;
  firstname = $('add_firstname').value;

  vars['lastname'] = lastname;
  vars['firstname'] = firstname;

  srvpath = '/spiderfrock/' + adrbook + '/ajaxaddperson';

  ajaxCaller.postForPlainText(srvpath, vars, ReturnAddNew)
}

function ReturnAddNew(id_newstring) {
    info_array = id_newstring.split("\t");
    if (info_array[0].substring(0,1).toLowerCase() == 's') {
        id = info_array[1];
        lastname = $("add_lastname").value.substr(0,1).toUpperCase() + $("add_lastname").value.substr(1);
        firstname = $("add_firstname").value.substr(0,1).toUpperCase() +  $("add_firstname").value.substr(1);
        theop = lastname + ', ' + firstname + '\t' + id;
        newname = lastname + ', ' + firstname;
        add_to_list(newname, theop, 'yes');
        $("add_lastname").value = '';
        $("add_firstname").value = '';
        $("addstatus").innerHTML = 'Record Successfully Added';
    }
    else {
        $("addstatus").innerHTML = 'ERROR: Record could not be added';
    }
    fade('addstatus');
}

// Caller-friendly front-end to fadeLoop
function fade(thewebpage) {
  fadeLoop(0, thewebpage);
}

// Initially set to yellow - "rgb(100%, 100%, 0%)". Blue component is 
// stepped up 10% every 100 milliseconds until the target colour of white 
// - "rgb(100%, 100%, 100%)" - has been reached.
function fadeLoop(nextBluePercent, thewebpage) {
  $(thewebpage).style.backgroundColor = "rgb(100%, 100%, "+nextBluePercent+"%)";
  $(thewebpage).style.color = "rgb("+nextBluePercent+"%, "+nextBluePercent+"%, "+nextBluePercent+"%)";
  nextBluePercent += 5;
  if (nextBluePercent<=100) {
    setTimeout("fadeLoop("+nextBluePercent+",\"" + thewebpage + "\")", 100/*ms*/);
  }
}


function ajaxsavephone(fld_id, fld_id_0, oldvalue) {
    var vars = new Array();
    thevalue = $(fld_id_0).value;
    //alert('the phone value at fld_id_0 = ' + thevalue  + '  the old value = ' + oldvalue);
    $(fld_id).innerHTML = '';
    $(fld_id).innerHTML = thevalue;
    
    if (oldvalue != thevalue) {
        theparts = fld_id.split('_');
        vars['phone_id'] = theparts[1];
        vars['phone_number'] = thevalue;

        srvpath = '/spiderfrock/' + adrbook + '/ajaxfieldupdate/phone';
        ajaxCaller.postForPlainText(srvpath, vars, Return_Fieldupdate)
    }
}

function ajaxsavecustom(fld_id, fld_id_0, oldvalue) {
    var vars = new Array();
    thevalue = $(fld_id_0).value;
    $(fld_id).innerHTML = '';
    $(fld_id).innerHTML = thevalue;
    
    if (oldvalue != thevalue) {
        theparts = fld_id.split('_');
        vars['custom_id'] = theparts[1];
        vars['custom_data'] = thevalue;

        srvpath = '/spiderfrock/' + adrbook + '/ajaxfieldupdate/custom';
        ajaxCaller.postForPlainText(srvpath, vars, Return_Fieldupdate)
    }
}


function ajaxsavenote(fld_id) {
    var vars = new Array();
    fld_id_0 = fld_id + '_0';
    thevalue = $(fld_id_0).value;
    //$(fld_id).innerHTML = thevalue;
    fld_id_2 = fld_id + '_2';
    $(fld_id_2).value = '';
    $(fld_id_2).value = thevalue;
    
    oldvalue = '';
    if (oldvalue != thevalue) {
        theparts = fld_id.split('_');
        fld_id_private = fld_id + '_private'
        vars['isprivate'] = $(fld_id_private).checked;
        vars['person_id'] = theparts[1];
        vars['comment'] = thevalue;
        vars['fld_id'] = fld_id;

        if (vars['isprivate']) {
            $('nlabel_private').value = ' checked ';
        }
        else {
            $('nlabel_private').value = '';
        }

        srvpath = '/spiderfrock/' + adrbook + '/ajaxfieldupdate/note';
        ajaxCaller.postForPlainText(srvpath, vars, Return_Noteupdate)
    }
}


function ajaxsavedate(fld_id, fld_id_0, oldvalue) {
var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December');
    var vars = new Array();
    var dateparts = new Array();
    thevalue = $(fld_id_0).value;
    dateparts = thevalue.split('-');
    thedisplayvalue = MONTH_NAMES[parseInt(dateparts[1]) -1] + ' ' + dateparts[2] + ', ' + dateparts[0]; 

    //$(fld_id).innerHTML = thevalue;
    $(fld_id).innerHTML = '';
    $(fld_id).innerHTML = thedisplayvalue;
    
    if (oldvalue != thevalue) {
        theparts = fld_id.split('_');
        vars['date_id'] = theparts[1];
        vars['date'] = thevalue;

        srvpath = '/spiderfrock/' + adrbook + '/ajaxfieldupdate/date';
        ajaxCaller.postForPlainText(srvpath, vars, Return_Fieldupdate)
    }
    glb_dateedit_mode = 0;
}


function ajaxsaveemail(fld_id, fld_id_0, oldvalue) {
    //alert('made it to ajaxsaveemail fld_id = ' + fld_id);
    var vars = new Array();
    thevalue = $(fld_id_0).value;
    thelink = '<a href="mailto:' + thevalue + '">' + thevalue + '</a>'
    $(fld_id).innerHTML = '';
    $(fld_id).innerHTML = thelink;
    fld_id_2 = fld_id + '_2';
    $(fld_id_2).value = '';
    $(fld_id_2).value = thevalue;
    
    //alert('oldvalue = ' + oldvalue + '  thelink = ' + thelink);
    if (oldvalue != thelink) {
        theparts = fld_id.split('_');
        vars['email_id'] = theparts[1];
        vars['email'] = thevalue;

        //alert('CALL AJAX EMAILUPDATE');
        srvpath = '/spiderfrock/' + adrbook + '/ajaxfieldupdate/email';
        ajaxCaller.postForPlainText(srvpath, vars, Return_Fieldupdate)
    }
}

function ajaxsaveurl(fld_id, fld_id_0, oldvalue) {
    //alert('made it to ajaxsaveurl fld_id = ' + fld_id);
    var vars = new Array();
    thevalue = $(fld_id_0).value;
    thelink = '<a href="href' + thevalue + '">' + thevalue + '</a>'
    $(fld_id).innerHTML = '';
    $(fld_id).innerHTML = thelink;
    fld_id_2 = fld_id + '_2';
    $(fld_id_2).value = '';
    $(fld_id_2).value = thevalue;
    
    //alert('oldvalue = ' + oldvalue + '  thelink = ' + thelink);
    if (oldvalue != thelink) {
        theparts = fld_id.split('_');
        vars['url_id'] = theparts[1];
        vars['url'] = thevalue;

        //alert('CALL AJAX EMAILUPDATE');
        srvpath = '/spiderfrock/' + adrbook + '/ajaxfieldupdate/url';
        ajaxCaller.postForPlainText(srvpath, vars, Return_Fieldupdate)
    }
}

//
// Return Field update
//
function Return_Fieldupdate(id_newstring) {

//alert(id_newstring);
//alert('Made it to Return_Fieldupdate');

}

//
// Return Field update
//
function Return_Noteupdate(id_newstring) {

//alert(id_newstring);
    info_array = id_newstring.split("\t");
    $(info_array[0]).innerHTML = info_array[1]
//alert('Made it to Return_Fieldupdate');

}


function alabeledit(fld_id) {
    if (ck_max_customer()) {
        return;
    }
    // Be certain we only have the text
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit')) {
        fld_text = $(fld_id).innerHTML;
        fld_id_0 = fld_id + '_0';
        inputline = '<input  class="inputajax" onKeyPress="checkEnter(event, \'phone\',\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\')" onblur="ajaxsavephone(\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\' )" type="text" size="12" name="' + fld_id_0 + '"  id="' + fld_id_0 + '" value="' + fld_text + '" />';
        //alert("The inputline = " + inputline);
        $(fld_id).innerHTML =  inputline;
        $(fld_id_0).focus();
    }
}


function ajaxaddress2(fld_id) {
    var vars = new Array();
    vars['address_id'] = fld_id
    vars['address_block'] = $('streetid_' + fld_id).value; 
    vars['city'] = $('city_' + fld_id).value; 
    vars['state'] = $('state_' + fld_id).value; 
    vars['zip'] = $('zip_' + fld_id).value; 

    srvpath = '/spiderfrock/' + adrbook + '/ajaxfieldupdate/address_2';
    ajaxCaller.postForPlainText(srvpath, vars, Return_Address2)
   
}

function Return_Address2(id_newstring) {
    info_array = id_newstring.split("\t");
    $('adrlabel_' + info_array[0]).innerHTML = info_array[1];
}

function adrlabeledit(fld_id) {
    if (ck_max_customer()) {
        return;
    }
    // Be certain we only have the text
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit')) {
        var vars = new Array();
        
        theparts = fld_id.split('_');
        vars['address_id'] = theparts[1];

        srvpath = '/spiderfrock/' + adrbook + '/ajaxfieldupdate/address_1';
        ajaxCaller.postForPlainText(srvpath, vars, Return_Address1)
    }
}

function Return_Address1(id_newstring) {
    info_array = id_newstring.split("\t");
    $('adrlabel_' + info_array[0]).innerHTML = info_array[1];
    //alert('Return Address 1 ck_focus to zeor');
    ck_focus = 0;
    $('streetid_' + info_array[0]).focus()
    glb_time_opt = 'address';
    //timedCount(info_array[0]);
    t=setTimeout("timedCount(" + info_array[0] + ")",1000);

}

var  ck_focus = 0;
function setfocus(obj, rec_id) {
    //alert('Set Focus');
    ck_focus = ck_focus + 1;
    //alert('setfocus() ck_focus = ' + ck_focus);
}

function clearfocus(obj, rec_id) {
    ck_focus = ck_focus - 1;
    //alert('clearfocus() ck_focus = ' + ck_focus);
}

function timedCount(addr_id)
{
//alert('count id = ' + addr_id + '  ck_focus = ' + ck_focus);
if (ck_focus <= 0 ) {
    if (glb_time_opt == 'address') {
        ajaxaddress2(addr_id);
    }
    else if (glb_time_opt == 'note') {
        labelid = 'nlabel_' + addr_id;
        ajaxsavenote(labelid);
        //ajaxsavenote(addr_id);
    }
}
else {
    //alert('setTimeout addr_id = ' + addr_id);
    t=setTimeout("timedCount(" + addr_id + ")",1000);
}
}

function stopCount()
{
clearTimeout(t);
}

function clabeledit(fld_id) {
    if (ck_max_customer()) {
        return;
    }
    // Be certain we only have the text
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit')) {
        fld_text = $(fld_id).innerHTML;
        fld_id_0 = fld_id + '_0';
        inputline = '<input class="inputajax"  onKeyPress="checkEnter(event, \'custom\',\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\')" onblur="ajaxsavecustom(\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\' )" type="text" size="12" name="' + fld_id_0 + '"  id="' + fld_id_0 + '" value="' + fld_text + '" />';
        //alert("The inputline = " + inputline);
        $(fld_id).innerHTML =  inputline;
        $(fld_id_0).focus();
    }
}

function nlabeledit(fld_id, privatenoteck) {
    if (ck_max_customer()) {
        return;
    }
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit')) {
        privatenoteck = $('nlabel_private').value;
        glb_time_opt = 'note';
        fld_id_2 = fld_id + '_2';
        fld_text = $(fld_id_2).value;
        fld_id_0 = fld_id + '_0';
        fld_id_private = fld_id + '_private'
        inputline = '<input type="checkbox" ' + privatenoteck + 'id="' + fld_id_private + '" onfocus="setfocus(this)" onblur="clearfocus(this)" ><span class="edit_label"> Private</span><br/>' 
        inputline = inputline + '<textarea cols="40" rows="3"  onfocus="setfocus(this)" onblur="clearfocus(this)" class="inputajax"  onKeyPress="checkEnter(event, \'note\',\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\')" onblur="ajaxsavenote(\'' + fld_id + '\' )" type="text" size="12" name="' + fld_id_0 + '"  id="' + fld_id_0 + '" />' + fld_text + '</textarea>';
        //alert("The inputline = " + inputline);
        $(fld_id).innerHTML =  inputline;
        $(fld_id_0).focus();

        theparts = fld_id.split('_');
        timedCount(theparts[1]);
    }
}

function elabeledit(fld_id) {
    if (ck_max_customer()) {
        return;
    }
    // Be certain we only have the text
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit')) {
        fld_id_2 = fld_id + '_2';
        fld_text = $(fld_id_2).value;
        fld_id_0 = fld_id + '_0';
        inputline = '<input class="inputajax" onKeyPress="checkEnter(event, \'email\',\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\')" onblur="ajaxsaveemail(\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\' )" type="text" size="24" name="' + fld_id_0 + '"  id="' + fld_id_0 + '" value="' + fld_text + '" />';
        //alert("The inputline = " + inputline);
        $(fld_id).innerHTML =  inputline;
        $(fld_id_0).focus();
    }
}

function ulabeledit(fld_id) {
    if (ck_max_customer()) {
        return;
    }
    // Be certain we only have the text
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit')) {
        fld_id_2 = fld_id + '_2';
        fld_text = $(fld_id_2).value;
        fld_id_0 = fld_id + '_0';
        inputline = '<input class="inputajax" onKeyPress="checkEnter(event, \'url\',\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\')" onblur="ajaxsavedate(\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\' )" type="text" size="30" name="' + fld_id_0 + '"  id="' + fld_id_0 + '" value="' + fld_text + '" />';
        $(fld_id).innerHTML =  inputline;
        $(fld_id_0).focus();
    }
}

function dlabeledit(fld_id) {
    if (ck_max_customer()) {
        return;
    }
    // Be certain we only have the text
    s =  $('id_security').value;
    if ((s == 'admin') || (s == 'edit')) {
        fld_id_2 = fld_id + '_2';
        fld_text = $(fld_id_2).value;
        fld_id_0 = fld_id + '_0';
        inputline = '<input class="inputajax" onKeyPress="checkEnter(event, \'date\',\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\')" onblur="ajaxsavedate(\'' + fld_id + '\',\'' + fld_id_0 + '\'' + ',\'' + fld_text + '\' )" type="text" size="10" name="' + fld_id_0 + '"  id="' + fld_id_0 + '" value="' + fld_text + '" />';
        $(fld_id).innerHTML =  inputline;
        $(fld_id_0).focus();
        glb_dateedit_mode = 1;
    }
}

function EditRemindInfo(adrbook, id){
    var vars = new Array();

    vars['userdate_id'] = id;

    if ($('ideditsave_' + id).value == 'Edit'){
        $('ideditsave_' + id).value = 'Save';
        srvpath = "/spiderfrock/" + adrbook + '/ajaxupdate/getremindinfo/';
        ajaxCaller.postForPlainText(srvpath, vars, ReturnRemindInfo)
    } else
    {
        $('ideditsave_' + id).value = 'Edit';
        thedate  = $('idthedate_' + id).value;
        userdate = $('idruserdate_' + id).value;
        //remind1 = $('idrremind1_' + id).value;
        remind1 = $('idrremind1_' + id).options[ $('idrremind1_' + id).selectedIndex].value;
        remind2 = $('idrremind2_' + id).value;
        email = $('idremail_' + id).value;
        appendtext = $('idrappendtext_' + id).value;
        vars['userdate_id'] = id;
        vars['thedate'] = userdate;
        vars['remind1'] = remind1;
        vars['remind2'] = remind2;
        vars['email'] = email;
        vars['appendtext'] = appendtext;
        srvpath = "/spiderfrock/" + adrbook + '/ajaxupdate/setremindinfo/';
        ajaxCaller.postForPlainText(srvpath, vars, ReturnRemindInfo)
    }
}

function ReturnRemindInfo(id_newstring) {
    //alert(id_newstring);
    info_array = id_newstring.split("\t");
    id = info_array[1];
    $('idthedate_' + id).innerHTML = info_array[2];
    $('idremind1_' + id).innerHTML = info_array[3];
    $('idremind2_' + id).innerHTML = info_array[4];
    $('idemail_' + id).innerHTML = info_array[5];
    $('idappendtext_' + id).innerHTML = info_array[6];
}
