var OldColor = "";
var focusField = "";

/* Functions that swaps images. */
function MM_swapImage() {
    //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;
  document.MM_sr=new Array;
  for(i=0;i<(a.length-2);i+=3)
    if ((x=MM_findObj(a[i]))!=null) {
        document.MM_sr[j++]=x;
        if(!x.oSrc)
            x.oSrc=x.src;
        x.src=a[i+2];
    }
}

function MM_swapImgRestore() {
    //v3.0
    var i,x,a=document.MM_sr;
    for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++)
        x.src=x.oSrc;
}

/* Functions that handle preload. */
function MM_preloadImages() { //v3.0
    var d=document;
    if(d.images) {
        if(!d.MM_p)
            d.MM_p=new Array();
        var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
        for(i=0; i<a.length; i++)
            if (a[i].indexOf("#")!=0) {
                d.MM_p[j]=new Image;
                d.MM_p[j++].src=a[i];
            }
    }
}

function P7_Snap() { //v2.63 by PVII
 var x,y,ox,bx,oy,p,tx,a,b,k,d,da,e,el,tw,q0,xx,yy,w1,pa='px',args=P7_Snap.arguments;a=parseInt(a);
 if(document.layers||window.opera){pa='';}for(k=0;k<(args.length);k+=4){
 if((g=MM_findObj(args[k]))!=null){if((el=MM_findObj(args[k+1]))!=null){
 a=parseInt(args[k+2]);b=parseInt(args[k+3]);x=0;y=0;ox=0;oy=0;p="";tx=1;
 da="document.all['"+args[k]+"']";if(document.getElementById){
 d="document.getElementsByName('"+args[k]+"')[0]";if(!eval(d)){
 d="document.getElementById('"+args[k]+"')";if(!eval(d)){d=da;}}
 }else if(document.all){d=da;}if(document.all||document.getElementById){while(tx==1){
 p+=".offsetParent";if(eval(d+p)){x+=parseInt(eval(d+p+".offsetLeft"));y+=parseInt(eval(d+p+".offsetTop"));
 }else{tx=0;}}ox=parseInt(g.offsetLeft);oy=parseInt(g.offsetTop);tw=x+ox+y+oy;
 if(tw==0||(navigator.appVersion.indexOf("MSIE 4")>-1&&navigator.appVersion.indexOf("Mac")>-1)){
  ox=0;oy=0;if(g.style.left){x=parseInt(g.style.left);y=parseInt(g.style.top);}else{
  w1=parseInt(el.style.width);bx=(a<0)?-5-w1:-10;a=(Math.abs(a)<1000)?0:a;b=(Math.abs(b)<1000)?0:b;
  x=document.body.scrollLeft+event.clientX+bx;y=document.body.scrollTop+event.clientY;}}
 }else if(document.layers){x=g.x;y=g.y;q0=document.layers,dd="";for(var s=0;s<q0.length;s++){
  dd='document.'+q0[s].name;if(eval(dd+'.document.'+args[k])){x+=eval(dd+'.left');y+=eval(dd+'.top');
  break;}}}e=(document.layers)?el:el.style;xx=parseInt(x+ox+a),yy=parseInt(y+oy+b);
 if(navigator.appVersion.indexOf("MSIE 5")>-1 && navigator.appVersion.indexOf("Mac")>-1){
  xx+=parseInt(document.body.leftMargin);yy+=parseInt(document.body.topMargin);}
 e.left=xx+pa;e.top=yy+pa;}}}
}

function MM_openBrWindow(theURL,winName,features) {
    var new_win = window.open(theURL,winName,features);
    return new_win;
    /*
    Some window parameters are
    height          = denotes the height of the window in pixels.
    width               = denotes the width of the window in pixels.
    toolbar         = denotes if there will be a toolbar on the newly opened window. Set this to yes if you want one - no if you don't.
    menubar         = denotes if there will be a menubar. Set this to yes if you want one - no if you don't.
    scrollbars  = denotes if there will be scrollbars or not. Ditto with the yes and no deal. I wouldn't make a new window that would need scrollbars anyway. I think it kills the effect.
    resizable       = denotes if the user can change the size of the window by dragging or not.
    location        = denotes if there will be a location bar on the newly opened window. Use yes and no again.
    directories = denotes if there will be a directories bar on the new window. Use yes and no.
    status          = denotes if there will be a status bar. Use yes and no.
    */
}

function highlightrow(theRow, theColor)
{
    // if we're macintosh, punch out.
    if (navigator.userAgent.indexOf('Mac') != -1) { return true; }

    if (typeof(theRow.style) == 'undefined' || typeof(theRow.cells) == 'undefined') { return false; }

    var row_cells_cnt = theRow.cells.length;
    // Save the old color.........
    OldColor = theRow.cells[0].bgColor;
    for (var i = 0; i < row_cells_cnt; i++) {   theRow.cells[i].bgColor = theColor; }

    return true;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function P7_autoLayers() { //v1.2 by PVII
 var g,b,k,f,args=P7_autoLayers.arguments;
 var a = parseInt(args[0]);if(isNaN(a))a=0;
 if(!document.p7setc) {p7c=new Array();document.p7setc=true;
  for (var u=0;u<10;u++) {p7c[u] = new Array();}}
 for(k=0; k<p7c[a].length; k++) {
  if((g=MM_findObj(p7c[a][k]))!=null) {
   b=(document.layers)?g:g.style;b.visibility="hidden";}}
 for(k=1; k<args.length; k++) {
  if((g=MM_findObj(args[k])) != null) {
   b=(document.layers)?g:g.style;b.visibility="visible";f=false;
   for(j=0;j<p7c[a].length;j++) {
    if(args[k]==p7c[a][j]) {f=true;}}
  if(!f) {p7c[a][p7c[a].length++]=args[k];}}}
}

function MM_reloadPage(init) {  //Updated by PVII. Reloads the window if Nav4 resized
  if (init==true)
    with (navigator) {
        if ((appName=="Netscape") && (parseInt(appVersion)==4)) {
            document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage;
        }
    }
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function P7_ReDoIt() { //v1.21 by PVII
 if(document.layers) {MM_reloadPage(false);}
}

function getAdate(ret_form, ret_field, allow_past_sel) {
    var script_name = "datepicker";
    if (allow_past_sel) { script_name = script_name + "3"; }
    var win_to_open = script_name + ".html?form_name=" + ret_form + "&field_name=" + ret_field;
    datePicker = window.open(win_to_open, 'pickAdate','width=250,height=300,status=no');
  // datePicker = window.open(win_to_open);
}

/*******************************************************************
*** returns an installation name to the ret_field, and           ***
*** the installation record number to ret_hidden_field......     ***
*** UNLESS-->                                                    ***
***   if the ret_field = 'url', then the ret_hidden_field        ***
***   is treated as url querystring extras to pass back          ***
*******************************************************************/
//function get_installation(ret_form, ret_field, ret_hidden_field, losing) {
function get_installation(o) {
    var win_to_open = "get_installation.php?ret_form=" + o.ret_form + "&ret_field=" + o.ret_field + "&ret_hidden_field=" + o.ret_hidden_field + "&losing=" + o.losing + "&r=" + o.user_rights;
    window.open(win_to_open, 'pickinstallation','width=550,height=600,status=yes,scrollbars=yes,resizable=yes');
}

function get_user(ret_form, ret_firstname_field, ret_lastname_field, ret_hidden_field, ret_rights_field, ret_co_phone_field, ret_co_name_field, prn) {
    var win_to_open = "get_user.php?ret_form=" + ret_form +
                      "&ret_firstname_field=" + ret_firstname_field +
                      "&ret_lastname_field=" + ret_lastname_field +
                      "&ret_rights_field=" + ret_rights_field +
                      "&ret_co_phone_field=" + ret_co_phone_field +
                      "&ret_co_name_field=" + ret_co_name_field +
                      "&ret_hidden_field=" + ret_hidden_field +
                      "&prn=" + prn;
    window.open(win_to_open, 'pickuser','width=600,height=430,status=yes,scrollbars=yes,resizable=yes');
}

function get_property(ret_form, ret_field, ret_hidden_field) {
    var win_to_open = "get_property.php?ret_form=" + ret_form + "&ret_field=" + ret_field + "&ret_hidden_field=" + ret_hidden_field;
    window.open(win_to_open, 'pickuser','width=550,height=430,status=yes,scrollbars=yes,resizable=yes');
}



function SubmitForm(FormName) {
    document.forms[FormName].submit();
}

function areyousure(texttoask) {
    return confirm("Are you sure you want to " + texttoask + "?\n\nClick OK for yes, and CANCEL for no");
}

function setFieldFocus(focusField) {
    var theField = MM_findObj(focusField);
    if (theField)   { theField.focus(); }
}

function next_field(current_field, num_chars, next_field_focus) {
    var curField = MM_findObj(current_field);
    var nextField = MM_findObj(next_field_focus);
    if ((curField) && (next_field)) {
        var curLength = curField.value.length
        if (curLength == num_chars) { nextField.focus(); }
    }
}

function check_one_selected(field_name) {
    var theField = MM_findObj(field_name);
    if (theField) {
        if (theField.value == "") {
            alert("Please select an item in the list");
            return false;
        }
    }
}

/*** two modes right now.....check_all, or toggle ***/
var check_boxes = true;
function toggle_all_checks(theFormname, theFieldName, check_mode) {
    var theForm = document.forms[theFormname];
    if (theForm) {
        for (i=0, n=theForm.elements.length; i<n; i++) {
            if (theForm.elements[i].name.indexOf(theFieldName) != -1) {
                if (check_mode == "check_all") {
                    checked = true;
                } else if (check_mode == "clear_all") {
                   checked = false;
                } else {
                   // uncomment the following line to actually toggle the checks on an individual basis
                    // checked = !theForm.elements[i].checked;
                    checked = check_boxes;
                }

                if (theForm.elements[i].disabled == false) {
                    theForm.elements[i].checked = checked;
                }
            }
        }
        check_boxes = !check_boxes;
    }
}

/*** two modes right now.....check_all, or toggle ***/
var check_radios = true;
function toggle_all_radios(theFormname, theFieldName, value_to_search_for) {
    var theForm = document.forms[theFormname];
    if (theForm) {
        for (i=0, n=theForm.elements.length; i<n; i++) {
            if (theForm.elements[i].name.indexOf(theFieldName) != -1) {
                if (theForm.elements[i].value == value_to_search_for) {
                    // theForm.elements[i].checked = check_radios;
                    theForm.elements[i].click();
                }
            }
        }
        check_radios = !check_radios;
    }
}

function checkPicUpload(){
    if(document.forms.upload.pic_desc.value != ""){
        return true;
    }
    else{
        alert("You need to enter a description first.");
        return false;
    }
}


/***********************************
*** menu magic                   ***
***********************************/

   function P7_getHW(t,a) { //v2.07 by PVII
     var r,p,h=0,w=0;if((p=MM_findObj(a)) !=null){
     if(document.all || document.getElementById){h=parseInt(p.offsetHeight);w=parseInt(p.offsetWidth);
     if(!h){h=parseInt(p.style.pixelHeight);w=parseInt(p.style.pixelWidth);}
     }else if(document.layers){h=parseInt(p.clip.height);w=parseInt(p.clip.width);}}
     if(t=="width"){r=w;}else{r=h;}return r;
   }

   function P7_MM1dwt() { //v2.07 by PVII
     var g,lh,sw,fr = false;
     if(!document.p7mc)return;
     for(var x=0;x<p7m1.length;x++){tl=p7m1[x].id;lh="P7CM1DWT0"+tl;
    if((g=MM_findObj(lh)) !=null){fr=true;sw=0;break;}
    lh="P7CM1DWT1"+tl;if((g=MM_findObj(lh)) !=null){fr=true;sw=1;break;}}
     if(fr){eval("P7_trigMenuMagic1('"+tl+"',"+sw+")");}
   }

   function P7_setMenuMagic1() { //v2.07 by PVII
     var s,d,g,g2,gg,ww,kx,th,tu,ts,nu,xx,k=0,pa=0;args=P7_setMenuMagic1.arguments;
     if((parseInt(navigator.appVersion)>4 || navigator.userAgent.indexOf("MSIE")>-1)&& navigator.userAgent.indexOf("Opera")==-1){pa="px";}
     if(navigator.userAgent.indexOf("Opera")>-1){P7OperaW=window.innerWidth;P7OperaH=window.innerHeight;}
     if(!document.p7mc) { p7m3=new Array();
      p7m=new Array();document.p7mc=true;p7ms=new Array();document.P7_imswap=new Array();document.P7_imswapo=new Array();
      p7m1=new Array();p7m2=new Array();p7mprop=new Object();p7mprop.p7offset=args[0];p7mprop.p7rate=args[1];
      p7mprop.p7delay=args[2];p7mprop.p7bottom=args[3];
      if(document.layers){p7mprop.p7pageh = document.height;}}
     for(var x=4;x<args.length;x+=3){if((g=MM_findObj(args[x])) !=null){
       p7m[k]=args[x];g.p7imname=args[x+2];g.p7sub=args[x+1];p7m3[k]=0;
       g2=MM_findObj(args[x+2]);tu=g2.src;ts=tu.lastIndexOf(".");
       nu=tu.substring(0,ts)+"_open"+tu.substring(ts,tu.length);
    nu2=tu.substring(0,ts)+"_over"+tu.substring(ts,tu.length);
       document.P7_imswap[k]=new Image();document.P7_imswap[k].src=nu;
    document.P7_imswapo[k]=new Image();document.P7_imswapo[k].src=nu2;k++;}}
     var lf=0;for (var j=0;j<p7m.length;j++){
      if((g=MM_findObj(p7m[j])) !=null){d=(document.layers)?g:g.style;p7m1[j]=g;g.p7waiting=false;
       if(j==0){lf=parseInt(d.left);th=parseInt(d.top);}
       if(j>0){d.left=(lf+pa);th+=P7_getHW('height',p7m[j-1]);d.top=(th+pa);}
       if((s=MM_findObj(g.p7sub)) !=null){p7m2[j]=s;ww=P7_getHW('width',g.p7sub);
        kx=lf-ww-20;dd=(document.layers)?s:s.style;
        dd.left=(kx+pa);dd.top=(th+pa);p7ms[j]=th;dd.visibility="visible";s.p7open=false;s.p7waiting=false;}}}
     if((g=MM_findObj(p7mprop.p7bottom)) !=null){d=(document.layers)?g:g.style;
      d.left=(lf+parseInt(args[0])+pa);th+=P7_getHW('height',p7m[p7m.length-1]);d.top=(th+pa);}
   }

   function P7_BM1(el,x,y,a,b,c,s) { //v2.07 by PVII
    var g,elo=el,f="",m=false,d="";x=parseInt(x);y=parseInt(y);
    var t = 'g.p7BM = setTimeout("P7_BM1(\''+elo+'\',';
    if ((g=MM_findObj(el))!=null) {d=(document.layers)?g:g.style;}else{return;}
    var xx=(parseInt(d.left))?parseInt(d.left):0;
    var yy=(parseInt(d.top))?parseInt(d.top):0;
    var i=parseInt(a);
     if (eval(g.moved)){clearTimeout(g.p7BM);}
     if (xx<x){xx+=i;m=true;if(xx>x){xx=x;}}
     if (xx>x){xx-=i;m=true;if(xx<x){xx=x;}}
     if (yy<y){yy+=i;m=true;if(yy>y){yy=y;}}
     if (yy>y){yy-=i;m=true;if(yy<y){yy=y;}}
    if (m) {
     if((parseInt(navigator.appVersion)>4 || navigator.userAgent.indexOf("MSIE")>-1)&& navigator.userAgent.indexOf("Opera")==-1){
      xx+="px";yy+="px";}d.left=xx;d.top=yy;g.moved=true;eval(t+x+','+y+','+a+','+b+','+c+',0)",'+b+')');
     }else {g.moved=false;P7_wait(elo);}
   }

   function P7_wait(a) { //v2.07 by PVII
     var ma,mb;if((mb=MM_findObj(a)) !=null){
      if(!mb.p7waiting || mb.p7waiting=="none"){return;}
       ma=mb.p7waiting;mb.p7waiting=false;eval(ma);}
   }

   function P7_trigMenuMagic1(a,sw) { //v2.07 by PVII
     var x,g,gg,d,dd,w,lp,tp,im,im2,ts,nu,e,pa=0;if(!document.p7mc)return;
     if((parseInt(navigator.appVersion)>4 || navigator.userAgent.indexOf("MSIE")>-1)&& navigator.userAgent.indexOf("Opera")==-1){pa="px";}
     if(navigator.userAgent.indexOf("Opera")>-1){if( P7OperaW!=window.innerWidth || P7OperaH!=window.innerHeight)P7_setMenuMagic1();}
     var ofs=parseInt(p7mprop.p7offset),trt = parseInt(p7mprop.p7rate);
     var tdy=parseInt(p7mprop.p7delay),tsb,tlf,tst;for(x=0;x<p7m.length;x++){
     if(p7m[x]==a){d=p7m1[x];dd=(document.layers)?d:d.style;g=p7m2[x];gg=(document.layers)?g:g.style;
      e=MM_findObj(d.p7imname);im=e.src;ts=im.replace("_open","");ts=ts.replace("_over","");
      if(!g.p7open){tst="closed";im2=ts.lastIndexOf(".");
      nu=ts.substring(0,im2)+"_open"+ts.substring(im2,ts.length);ts = nu;}else{tst="open"}break;}}
     for(j=0;j<p7m.length;j++){
      d=p7m1[j];dd=(document.layers)?d:d.style;g=p7m2[j];gg=(document.layers)?g:g.style;
      if(j==0){tlf=parseInt(dd.left);}if(g.p7open){
      w=P7_getHW('width',d.p7sub)+20;w-=parseInt(dd.left);w*=-1;d.p7waiting=false;
      eval("P7_BM1('"+d.p7sub+"',"+w+","+parseInt(gg.top)+","+trt+","+tdy+",0,0)");}
      d.p7waiting=false;g.p7open=false;
      if(parseInt(sw)==1){e=MM_findObj(d.p7imname);im=e.src;im2=im.replace("_open","");e.src=im2;}}
     var tnt=new Array();var df=0,tcd=0,tdl=p7m[0];for(j=0;j<p7m.length;j++){
     d=p7m1[j];dd=(document.layers)?d:d.style;g=p7m2[j];gg=(document.layers)?g:g.style;
     if(j==0){th=parseInt(dd.top);}tnt[j]=th;df=Math.abs(parseInt(dd.top)-th);
     if(df>tcd){tdl=p7m[j];tcd=df;}th+=P7_getHW('height',p7m[j]);
     if(x==j && tst=="closed"){tsb=th;if(p7m3[j]!=1){th+=P7_getHW('height',d.p7sub);}}p7ms[j]=th;}
     if(tst=="closed"){d=p7m1[x];dd=(document.layers)?d:d.style;
      g=p7m2[x];gg=(document.layers)?g:g.style;lp=tlf+ofs;
      gg.top=(tsb+pa);p7ms[x]=tsb;e=MM_findObj(d.p7imname);if(parseInt(sw)==1){e.src=ts;}
      g.p7open=true;if(p7m3[x]!=1){gg.visibility="visible";var r;r=MM_findObj(tdl);
      r.p7waiting="P7_BM1('"+d.p7sub+"',"+lp+","+tsb+","+trt+","+tdy+",0,0)" ;}
      }else{d=p7m1[p7m1.length-1];d.p7waiting="none";}
     for(j=0;j<p7m.length;j++ ){eval("P7_BM1('"+p7m[j]+"',"+tlf+","+tnt[j]+","+trt+","+tdy+",0,0)");}
     if((g=MM_findObj(p7mprop.p7bottom)) !=null){d=(document.layers)?g:g.style;g.p7waiting=false;
      eval("P7_BM1('"+p7mprop.p7bottom+"',"+(tlf+ofs)+","+th+","+trt+","+tdy+",0,0)");
      th+=(document.layers)?P7_getHW('height',p7mprop.p7bottom):0;}
     if(document.layers){var tw2=document.width;
       if(document.height<th) {document.height=th;document.width=tw2;}}
   }

   function P7_rollCMenu1(ev,a,b) { //v2.07 by PVII
    var e,im,ts,j,nu,g,tev=ev.type;
    if(!document.p7mc)return;
    if(tev=="mouseover"){for(var x=0;x<p7m.length;x++){
    if(p7m[x]==a){g=p7m2[x];if(parseInt(b)==0 && g.p7open) {break;return;}
    e=MM_findObj(p7m1[x].p7imname);im=e.src;ts=im.replace("_open","");
    ts=ts.replace("_over","");j=ts.lastIndexOf(".");
    e.src=ts.substring(0,j)+"_over"+ts.substring(j,ts.length);break;}}
    }else if(tev=="mouseout"){for(var x=0;x<p7m.length;x++){
    if(p7m[x]==a){e=MM_findObj(d=p7m1[x].p7imname);im=e.src;
    g=p7m2[x];ts=im.replace("_open","");ts=ts.replace("_over","");
    if(g.p7open){j=ts.lastIndexOf(".");
    nu=ts.substring(0,j)+"_open"+ts.substring(j,ts.length);
    }else{nu=ts;}e.src=nu;break;}}}
   }

/***********************************
*** end menu magic               ***
***********************************/

/*
 * find_select_items
 *
 * An autoselect list for javascript
 * requires a global javascript array of values/display to search through!
 *
 * param search_source - form field for text box
 * param search_list   - select list to search in
 *
 * param search_array_values  - array of search values
 * param search_array_display - array of search display
 * NOTE:  The search values and search display need to be a 1-1 match!
 *
 *      for example, in your page, you HAVE to put in code similar to the following:
 *          <script language="javascript" type="text/javascript">
 *              var my_field_search_array  = new Array();
 *              var my_field_search_values = new Array();
 *          </script>
 *
 *      CRITICAL NOTE:  DO NOT FORGET THE ***NEW*** Array BECAUSE THAT CREATES AN
 *      ARRAY OBJECT THAT IS PASSED TO THE FUNCTION BY REFERENCE!!!
 *
 *      You must do that for EVERY text box you want to have a search for.
 *
 *      Then, call make a text box that has the following:
 *              onkeyup="find_select_items(this, this.form.elements['<form_element_to_search>'], my_field_search_values, my_field_search_array);"
 *
 *      A full example using draw_form_field looks like this:
 *
 *          echo '
 *          <script language="javascript" type="text/javascript">
 *              var f_my_select_list_values  = new Array();
 *              var f_my_select_list_display = new Array();
 *          </script>';
 *
 *          $form_field_search_opts['class']            = 'frminput';
 *          $form_field_search_opts['field_type']       = 'textbox';
 *          $form_field_search_opts['style']            = 'font-family: monospace; font-size: 11px; width: 420px';
 *          $form_field_search_opts['form_var_name']    = 'f_item_no_search';
 *          $form_field_search_opts['max_length']       = 25;
 *          $form_field_search_opts['javascript']       = 'onkeyup="find_select_items(this, this.form.elements[\'f_my_select_list\'], f_my_select_list_values, f_my_select_list_display);"';
 *
 *          echo draw_form_field($form_field_opts_search);
 *
 *          echo "<br /><br />";
 *
 *          $form_field_select_opts['class']            = 'frminput';
 *          $form_field_select_opts['field_type']       = 'select';
 *          $form_field_select_opts['style']            = 'font-family: monospace; font-size: 11px; width: 420px';
 *          $form_field_select_opts['form_var_name']    = 'f_my_select_list';
 *          $form_field_select_opts['multi']            = true;
 *          $form_field_select_opts['size']             = 10;
 *          $form_field_select_opts['sql']              = "SELECT clock_num, name FROM employees WHERE siteid = 'fletc' ORDER BY name";
 *
 *          echo draw_form_field($form_field_select_opts);
 */

// make a global variable to access all of the arrays the user may make
var find_select_arr;
function find_select_items(search_source, search_list, search_array_values, search_array_display, search_default_options) {

    if (!search_source || !search_list || !search_array_values || !search_array_display) { return false; }

    // *** let's create an array of values on the fly if necessary.
    if (search_array_values.length == 0) {
        for(i = 0; i < search_list.options.length; i++) {
            search_array_values[i]  = search_list.options[i].value;
            search_array_display[i] = search_list.options[i].text;
        }
    }

    var clean_reg = new RegExp("[^A-Z0-9 ^$\.-]", "gi");
    var search_pattern = search_source.value.replace(clean_reg, "");

    re = new RegExp(search_pattern, "gi");

    search_list.length = 0;         // Clear the options list
    var cur_list_item  = 0;         // set the pointer
    var check_length   = 1;         // if the drop down box has this many items, select automagically

    // if we have a default array, populate it here
    if (search_default_options) {
        for(i = 0; i < search_default_options.length; i++) {
            search_list[cur_list_item++] = new Option(search_default_options[i][1], search_default_options[i][0]);
        }

        var check_length = i + 1;
    }

    // *** Loop through the array and re-add matching options
    for(i = 0; i < search_array_display.length; i++) {
        if(search_array_display[i].search(re) != -1) {
            search_list[cur_list_item++] = new Option(search_array_display[i], search_array_values[i]);
        }
    }

    // When options list whittled to one, select that entry
    if(search_list.length == check_length) {
        search_list.options[check_length - 1].selected = true;

        // *** now, simulate the user clicking on the item
        var t_type = typeof search_list.click;

        // *** for IE, t_type = object, for firefox, it's undefined.  That's our key for now
            if (t_type == 'object') {
                search_list.click();
            } else {
                /* FireFox doesn't work
                alert (t_type);
                search_list.onclick;
                */
            }
    }

    return true;
}

// used in gothome to toggle fields on and off
function toggle_fields(type, show_alert) {

    var form_field_tmp;
    var groups_to_hide;
    var alert_msg = '';

    var cc = gid('propertycountry').value;

    var all_tbody_elements = Array(
        'tbody_alt_contact_info',
        'tbody_additional_fee',
        'tbody_approx_miles_to_base',
        'tbody_bah_information',
        'tbody_certify_mil_member',
        'tbody_community_name',
        'tbody_est_monthly_utils',
        'tbody_lease_terms',
        'tbody_military_benefits',
        'tbody_military_clause',
        'tbody_monthly_rent',
        'tbody_pets',
        'tbody_rpp',
        /* 'tbody_privitized_property', */
        'tbody_property_name',
        'tbody_security_deposit',
        'tbody_type_property',
        'tbody_userinfo',
        'tbody_utilities_included',
        'div_shared_bedroom_info_icon'
    );


    if (cc == 'GB') {

        var gb_fields = Array(
            'tbody_epc_ref',
            'tbody_epc_rating',
            'tbody_deposit_scheme'        
        );

        all_tbody_elements = all_tbody_elements.concat(gb_fields);
    } else {
        gb_fields = Array();
    }

    // turn them all on before we selectively hide
    for(var i = 0; i < all_tbody_elements.length; i++) {
        if (form_field_tmp = MM_findObj(all_tbody_elements[i])) {
            if (form_field_tmp.style.display == 'none') {
                form_field_tmp.style.display = '';
            }   // '' sets to default
        }
    }

    // reset the rent and sale price labels to their defaults
    if (form_field_tmp = MM_findObj('monthly_rent_label')) { form_field_tmp.style.display = ''; }
    if (form_field_tmp = MM_findObj('sale_price_label'))   { form_field_tmp.style.display = 'none'; }
    if (form_field_tmp = MM_findObj('rate_price_label'))   { form_field_tmp.style.display = 'none'; }

    // reset the lease terms label to their defaults
    if (form_field_tmp = MM_findObj('lease_terms_label')) { form_field_tmp.style.display = ''; }
    if (form_field_tmp = MM_findObj('rate_terms_label'))  { form_field_tmp.style.display = 'none'; }

    // reset the lease-types to their defaults
    if (form_field_tmp = MM_findObj('leaseterms')) {

        // remove all but the please choose
        for(i = form_field_tmp.options.length - 1; i >= 1; i--) { form_field_tmp.remove(i); }

        if (cc != 'NO') {
            // add back in the defaults
            form_field_tmp.options[1] = new Option('Month to Month',    'Month to Month');
            form_field_tmp.options[2] = new Option('3 Months',          '3 Months');
            form_field_tmp.options[3] = new Option('6 Months',          '6 Months');
            form_field_tmp.options[4] = new Option('7 Months',          '7 Months');
            form_field_tmp.options[5] = new Option('9 Months',          '9 Months');
            form_field_tmp.options[6] = new Option('1 Year',            '1 Year');

            var next = 7;
            if (cc == 'US' || cc == 'IT' || cc == 'NO' || cc == 'TR') {
                form_field_tmp.options[next] = new Option('More than 1 Year',   'More than 1 Year');
                next++;

            }

            form_field_tmp.options[next] = new Option('Negotiable', 'Negotiable');
        } else {
            form_field_tmp.options[1] = new Option('Month to Month',    'Month to Month');
            form_field_tmp.options[2] = new Option('2 Years',           '2 Years');
            form_field_tmp.options[3] = new Option('3 years or longer', '3 years or longer');

        }
    }

    /*  handled in post vars in php.
    if (type == 'mil') {
        document.GotHome.ppv[0].checked = true;     // set ppv to true
    } else {
        document.GotHome.ppv[0].checked = false;        // set ppv to true
    }

    */

    // reset the price field to empty
    // we're going to hijack the show_alert box here...........the script that fires at the bottom of the page uses this flag to suppress messages on post........
    // we'll use the same rule to avoid stomping on the rent amount.
    if (show_alert) {
        if (form_field_tmp = MM_findObj('pricepermonth'))       { form_field_tmp.value = ''; }
    }

    // now turn off what we need
    switch(type) {
        case 'mil':
        case 'govt':

            if (show_alert) {
                if (type == 'mil') {
                    alert_msg = 'By selecting MHPI (Privatized), you are either a Housing Office or \na Privatization Contractor and are managing on-base military housing.';
                } else {
                    alert_msg = 'By selecting Government Controlled, you are either a Housing Office or \na Government Controlled Contractor and are managing on-base military housing.';
                }
            }

            groups_to_hide = Array(
                'tbody_certify_mil_member',
                'tbody_est_monthly_utils',
                'tbody_lease_terms',
                'tbody_military_benefits',
                'tbody_military_clause',
                'tbody_monthly_rent',
                'tbody_privitized_property',
                // 'tbody_property_name',
                'tbody_rpp',
                'tbody_security_deposit',
                'div_shared_bedroom_info_icon'
            );

            if (cc == 'GB') {
                groups_to_hide = groups_to_hide.concat(gb_fields);
            }
            break;

        case 'sale':

            if (show_alert) {
                alert_msg = 'In order to enter a For Sale by Owner listing in AHRN you must be a military member or DoD Civilian employee and the house/unit must not be under contract with a licensed realtor.';
            }

            groups_to_hide = Array(
                'tbody_additional_fee',
                'tbody_bah_information',
                'tbody_lease_terms',
                'tbody_military_benefits',
                'tbody_pets',
                'tbody_military_clause',
                'tbody_pets',
                'tbody_property_name',
                'tbody_rpp',
                'tbody_security_deposit',
                'tbody_utilities_included',
                'tbody_privitized_property',
                'div_shared_bedroom_info_icon'
            );
                                      
            if (cc == 'GB') {
                groups_to_hide = groups_to_hide.concat(gb_fields);
            }


            // turn off the rent and rate labels and turn on the sale price label
            if (form_field_tmp = MM_findObj('monthly_rent_label'))  { form_field_tmp.style.display = 'none'; }
            if (form_field_tmp = MM_findObj('rate_price_label'))    { form_field_tmp.style.display = 'none'; }
            if (form_field_tmp = MM_findObj('sale_price_label'))    { form_field_tmp.style.display = ''; }

            break;

        case 'temp':

            // add the types to our lease terms dropdown
            if (form_field_tmp = MM_findObj('leaseterms')) {
                // move everything down two steps
                for(i = form_field_tmp.options.length - 1; i >= 1; i--) {
                    // form_field_tmp.options[i+2] = new Option(form_field_tmp.options[i].text, form_field_tmp.options[i].value);
                    form_field_tmp.remove(i);
                }
                form_field_tmp.options[1] = new Option('Daily',             'Daily');
                form_field_tmp.options[2] = new Option('Weekly',            'Weekly');
                form_field_tmp.options[3] = new Option('Monthly',           'Month to Month');
                form_field_tmp.options[4] = new Option('Call for Pricing',  'Call');
                // form_field_tmp.options[4] = new Option('Yearly',  '1 Year');
            }

            // turn off the lease terms label and turn on the rate terms label
            if (form_field_tmp = MM_findObj('lease_terms_label')) { form_field_tmp.style.display = 'none'; }
            if (form_field_tmp = MM_findObj('rate_terms_label'))  { form_field_tmp.style.display = ''; }

            // turn off the rent and sale labels and turn on the rate price label
            if (form_field_tmp = MM_findObj('monthly_rent_label'))  { form_field_tmp.style.display = 'none'; }
            if (form_field_tmp = MM_findObj('rate_price_label'))    { form_field_tmp.style.display = ''; }
            if (form_field_tmp = MM_findObj('sale_price_label'))    { form_field_tmp.style.display = 'none'; }

            groups_to_hide = Array(
                'tbody_bah_information',
                'tbody_certify_mil_member',
                'tbody_military_clause',
                'tbody_utilities_included',
                'div_shared_bedroom_info_icon'
            );

            if (cc == 'GB') {
                groups_to_hide = groups_to_hide.concat(gb_fields);
            }

            break;

        case 'rental':

            groups_to_hide = Array(
                'tbody_bah_information',
                'tbody_certify_mil_member',
                'div_shared_bedroom_info_icon'
            );

            break;

        case 'shared':

            groups_to_hide = Array(
                'tbody_additional_fee',
                'tbody_bah_information',
                'tbody_certify_mil_member'
            );

            if (cc == 'GB') {
                groups_to_hide = groups_to_hide.concat(gb_fields);
            }

            break;

    }

    if (groups_to_hide) {
        for(i = 0; i < groups_to_hide.length; i++) {
            if (form_field_tmp = MM_findObj(groups_to_hide[i])) {
                form_field_tmp.style.display = 'none';  // hide it
            }
        }
    }

    // reselect the lease terms here
    if (form_field_tmp = MM_findObj('leaseterms')) {
        var orig_lease_terms_field = MM_findObj('orig_leaseterms');
        orig_lease_terms_value = (orig_lease_terms_field) ? orig_lease_terms_field.value : '';
        for(i = 0; i < form_field_tmp.options.length; i++) {
            if (orig_lease_terms_value == form_field_tmp.options[i].value) { form_field_tmp.selectedIndex = i; break; }
        }
    }

    //refresh map
    //ahrn_mapping.gh_geocode({'zip_change':0});

    // after we're all done, if we have an alert to show, do it.
    if (alert_msg) { alert(alert_msg); }


}

function display_add_prop_disclaimer(type_added) {

    return true;

    /*

    var type_desc;

    switch(type_added) {
        case 'rental':
            type_desc = 'Rental';
            break;

        case 'shared':
            type_desc = 'Shared Rental';
            break;

        case 'sale':
            type_desc = 'For Sale';
            break;

        case 'mil':
            type_desc = 'Military Housing';
            break;

        case 'temp':
            type_desc = 'Temporary Lodging';
            break;

    }

    return confirm('this is the disclaimer for type:  ' + type_desc + '.\n\nClick OK to continue, or Cancel to abort');
    */
}


function set_and_bail(city_field, city_disp_field, state_field, state_disp_field, zip_field, zip_disp_field, country_field, conutry_disp_field, city, state, zip, country) {

    if (tmp_form_field = opener.document.forms['GotHome'].elements[city_field])         { tmp_form_field.value = city; }
    if (tmp_form_field = opener.document.forms['GotHome'].elements[city_disp_field])    { tmp_form_field.value = city; }
    if (tmp_form_field = opener.document.forms['GotHome'].elements[state_field])        { tmp_form_field.value = state; }
    if (tmp_form_field = opener.document.forms['GotHome'].elements[state_disp_field])   { tmp_form_field.value = state; }
    if (tmp_form_field = opener.document.forms['GotHome'].elements[zip_field])          { tmp_form_field.value = zip; }
    if (tmp_form_field = opener.document.forms['GotHome'].elements[zip_disp_field])     { tmp_form_field.value = zip; }
    if (tmp_form_field = opener.document.forms['GotHome'].elements[coutry_field])           { tmp_form_field.value = country; }
    if (tmp_form_field = opener.document.forms['GotHome'].elements[country_disp_field])     { tmp_form_field.value = country; }
    
    ahrn_mapping.gh_geocode({"zip_change":1, "add":0});
    
    window.close();
}

function hide_user_input_fields(branch) {

    var form_field_tmp;

    var all_tbody_elements = Array(
        'tbody_grade',
        'tbody_deps'
    );

    for(var i = 0; i < all_tbody_elements.length; i++) {
        if (form_field_tmp = MM_findObj(all_tbody_elements[i])) {
            if (form_field_tmp.style.display == 'none') {   
                form_field_tmp.style.display = '';
            }   // '' sets to default
        }
    }

    if (branch == 'CV' || branch == 'CV-C' || branch == 'CV-R') {
        var groups_to_hide = Array('tbody_grade', 'tbody_deps');
    }

    if (groups_to_hide) {
        for(i = 0; i < groups_to_hide.length; i++) {
            if (form_field_tmp = MM_findObj(groups_to_hide[i])) {
                form_field_tmp.style.display = 'none';  // hide it
            }
        }
    }

}

// used in wanthome to hide/show fields
function hide_div_layer(divs_to_hide) {

    var tmp;
    var all_div_layers = Array(
                               'div_bah_information'
                               );

    // turn all on
    for(var i = 0; i < all_div_layers.length; i++) {
        if (tmp = MM_findObj(all_div_layers[i])) {
            if (tmp.style.display == 'none') {
                tmp.style.display = '';         // '' sets to default
            }
        }
    }

    if (divs_to_hide) {
        for(i = 0; i < divs_to_hide.length; i++) {
            if (tmp = MM_findObj(divs_to_hide[i])) {
                tmp.style.display = 'none';     // hide it
            }
        }
    }
}

function set_div_vis(div_to_set, state_to_set) {    // state is '' (for default) or 'none' for hide

    if (tmp = MM_findObj(div_to_set)) {
        tmp.style.display = state_to_set;
    }

}


function set_opacity(obj, val) {

    if (typeof(obj) == 'string') { obj = document.getElementById(obj); }

    if (!obj) { return false; }

    if (obj.filters) {  //For IE

        val *= 100;
        try {
            obj.filters.item("DXImageTransform.Microsoft.Alpha").opacity = val;
        } catch (e) {
            // If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
            obj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+val+')';
        }
    } else {
        obj.style.opacity = val;
        obj.style.MozOpacity = val;  //This is for older Mozilla Browsers
    }
}

/* resets a dropdownbox to it's pristine state
 */
function reset_dropdown(search, select, values, display) {

    obj_search = document.getElementById(search);
    obj_select = document.getElementById(select);

    if (!obj_search || !obj_select) { return false; }

    obj_search.value = '';
    find_select_items(obj_search, obj_select, values, display);
    obj_select.selectedIndex=0;

}

/**
 * submit_rb
 *
 * function to submit a row button with only the necessary values
 * rather than submitting the entire form
 * (sweet helper)
 *
 * @param object formfield
 * @return void
 */
function submit_rb(form_field) {

    var ff = document.oneclick.f_btn_hidden;

    if (!ff) { return true; }   // if the hidden document isn't found, return true so the whole form gets submitted

    ff.name  = form_field.name;
    ff.value = form_field.value;

    document.oneclick.submit();
    return false;
}

function show_and_repos_div(offset_X, offset_Y, Div, event) {

    var divObject = document.getElementById(Div);
    if (!divObject) { return false; }

    // alert('X=' + event.clientX + ' Y=' + event.clientY);
    if (typeof(event) != 'undefined') {

         if (event.clientX || event.clientY) {
            var foo = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft + offset_X;
            divObject.style.left    = (event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft + offset_X) + 'px';
            divObject.style.top     = (event.clientY + document.documentElement.scrollTop  + document.body.scrollTop  + offset_Y) + 'px';
        }

    }

    divObject.style.display = '';
}

/**
 * select_all_text
 *
 * function to focus and select all text in a textbox
 *
 * @param mixed (object or string, field object or fieldname)
 * @return void
 */
var s_a_e;      // variable to determine whether or not we've already been here.
function select_all_text(f) {

    if (typeof(f) == 'string') { f = document.getElementById(f); }

    if (!f) { return false; }

    setTimeout(

        function() {
            try {
                f.focus();
                f.select();
            }

            catch (e) {

                if (e.number = -2146826178) {       // can't focus yet -- not visible yet -- animating?
                    if (!s_a_e) { select_all_text(f); }     // only try once more.
                    s_a_e = true;
                    return false;
                }

            }

            s_a_e = false;      // reset our flag

        },
        250
    );

}

function toggle_info_box() {

    var lih, liht;
    if (lih = document.getElementById('listing_info_hidden')) {

        lih.style.display = (lih.style.display == '') ? 'none' : '';

        if (liht = document.getElementById('lih_text')) {
            liht.innerHTML = (lih.style.display == 'none') ? 'View more info' : 'View less info';
        }

    }

}

function reset_print_summary() {

    try {

        if (typeof(opener) != 'undefined' && opener != null) {

            if (typeof(opener.document.want_home_summary) != 'undefined') {

                if (typeof(opener.document.want_home_summary.print_friendly) != 'undefined') {
                    opener.document.want_home_summary.print_friendly.value = '0';
                }

                if (typeof(opener.document.want_home_summary.target) != 'undefined') {
                    opener.document.want_home_summary.target = '';
                }

            }

        }

    } catch (e) { }

}

function enum_obj(obj) {
    var i, msg;
    for (i in obj) {
        msg += 'obj[' + i + '] = ' + obj[i] + '\\n';
    }
    alert(msg);
}

/* psm
 *
 * pcs send message
 *
 */
function psm(t, p) {   //p = page
    var s, f, q, ms, sb, tp, h;     // subject, msg header, send message button, message body, subject, template name, description text
    f = document.getElementById('send_msg_header');
    s = document.getElementById('f_msg_type');
    q = document.getElementById('f_send_msg');

    ms = document.getElementById('f_msg');
    sb = document.getElementById('f_subject');
    tp = document.getElementById('f_template');

    h  = document.getElementById('f_msg_help_text');

    // clear the old values
    if (tp) { tp.selectedIndex = 0; }
    if (sb) { sb.value = ''; }
    if (ms) { ms.value = ''; }

    if (!f || !s) { return false; }

    if (t == 'msg') {
        f.innerHTML = 'Send a Message';
        s.value = 'message';
        q.value = 'Send Message';
        if (h) {
            switch(p) {

                case 'pp':
                    h.innerHTML = 'This will send a message within the AHRN enclosed messaging system.<br><br>Choose a template eWelcome message, select Create New Template or create and send a single new message, click Send Message (will not save) or Save as Template for future use.';
                    break;
                case 'um':
                    h.innerHTML = 'This will send a message within the AHRN enclosed messaging system.<br><br>Choose a template (once created), select Create New Template or create and send a single new message, click Send Message (will not save) or Save as Template for future use.';
            }
        }
    } else {
        f.innerHTML = 'Send an Email';
        s.value = 'email';
        q.value = 'Send Email';
        if (h) {
            switch(p) {
                case 'pp':
                    h.innerHTML = 'This will send a message to users personal email address outside the AHRN enclosed messaging system.<br><br>Choose a template eWelcome message,  select Create New Template or create and send a single new email, click Send Email (will not save) or Save as Template for future use.';
                    break;
                case 'um':
                    h.innerHTML = 'This will send a message to users personal email address outside the AHRN enclosed messaging system.<br><br>Choose a template (once created),  select Create New Template or create and send a single new email, click Send Email (will not save) or Save as Template for future use.';
                    break;
            }

        }
    }

}

/**
 * voc
 *
 * function to verify if at least one checkmark is selected
 *
 * @param  mixed string or object - form_name or form object
 * @param  string field_name
 * @return bool   true if any are checked or false if not
 */
function voc(frm, fld) {

    var fr, i;

    fr = (typeof(frm) == 'string') ? document.getElementById(frm) : frm;
    if (!fr) { return false; }

    if (!fr.elements) { return false; }

    for (i = 0; i < fr.elements.length; i++) {

        if (fr.elements[i].name && fr.elements[i].name.indexOf(fld) != -1) {
            if (fr.elements[i].checked == true) { return true; }
        }

    }

    return false;

}

function open_msg_frm(frm, t, e, p) {

    if (!voc(frm, 'f_checked')) {
        alert('You must select at least one recipient');
        return false;
    }

    psm(t,p);
    rbp.move_form('message_body', e);
    return false;

}

function get_tpl_name() {

    var t, cv, f;

    f = document.getElementById('f_template');

    if (f) { cv = f.value; }

    if (cv == 'Create New Template') { cv = ''; }

    t = prompt('Please enter a name of the new template or hit "OK" to save changes to an existing template.', cv);
    if (t == null) { return false; }

    if (t == '') {
        alert('You must enter a valid template name');
        return get_tpl_name();
    }

    if (t == 'Create New Template') {
        alert('You cannot save a template with that name.  Please enter a different template name');
        return get_tpl_name();
    }

    return t;

}



/**
 * select list management, if "all" is selected unchecks any other options
 * if other options are selected "all" is deselected
 */
function sall(elem) {


    if (elem.selectedIndex == 0) {

        //Unselect all the others
        for (var i = 1; i <= elem.length - 1; i++) {
            elem.options[i].selected = false;
        }

    }
}



function unsaved_checked() {

    if (document.input_check.toggle.value == 1) {
        if (!confirm('You have unsaved changes!  Do you want to proceed and discard your changes?\n\nClick OK for yes, or Cancel to return to the summary page')) {
            return false;
        }
    }

    return true;
}

/***
 * Checks/Sets cookie based on user setting to identify
 * whether or not to show the IE6 and older message
  */
function set_browser_check_cookie(action) {

    //alert(action);

    var expiredays;
    var c_value;

     // Determine the users preferences
    if (action == 1) {
        // Remind me
        expiredays = 14; // two weeks
        c_value = 'Remind';

    } else if (action == 0) {
        // Never remind me
        expiredays = 365; // can't really be never so how about a year
        c_value = 'Never';
    }

    var expdate = new Date();

    expdate.setDate(expdate.getDate() + expiredays);
    var expiredate = expdate.toGMTString()

    document.cookie= "AHRN_Browser_Check=" + c_value +"|" + expiredate + ";expires=" + expiredate;

    document.getElementById('browser_check').style.display = "none";

    return true;
}



/**
 * Set Focus - Index page
 */
function sf(form_name, field_name) {
    // get the form object
    var the_form = document.forms[form_name];

    // if we have a form object, get the field object and set the focus
    if (the_form) {
        the_field = the_form.elements[field_name];
        if (the_field) { the_field.focus(); the_field.select(); }
    }
}



/** AHRS_SHELL **/

/**
 * Add event to load when DOM is ready
 */
function addLoadEvent(func) {

    var oldonload = window.onload;

    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {

            if (typeof(oldonload) == 'function') {
                oldonload();
            }

            func();
        }
    }
}


var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
var browser = {
    version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
    safari: /webkit/.test( userAgent ),
    opera: /opera/.test( userAgent ),
    msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
    mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};


// DOM Readiness
var readyBound = false;     //Has DOMReady already been executed
var isReady    = false;     //Flag to indicate whether DOM is ready

function DOMReady(fn) {

    // Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
    if ( document.addEventListener && !browser.opera && !browser.safari) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", fn, false );
        return;
    }

    // If IE is used and is not in a frame
    // Continually check to see if the document is ready
    if ( browser.msie && window == top ) (function(){
        if (isReady) return;
        try {
            document.documentElement.doScroll("left");
        } catch( error ) {
            setTimeout( arguments.callee, 0 );
            return;
        }
        // and execute any waiting functions
        isReady = true;
        eval(fn);

    })();

    // Opera
    if ( browser.opera )
        document.addEventListener( "DOMContentLoaded", function () {
            if (isReady) return;
            for (var i = 0; i < document.styleSheets.length; i++)func
                if (document.styleSheets[i].disabled) {
                    setTimeout( arguments.callee, 0 );
                    return;
                }
            // and execute any waiting functions
            isReady = true;
            eval(fn);
        }, false);

    // Safari
    if ( browser.safari ) {
        var numStyles;
        (function(){
            if (isReady) return;
            if ( document.readyState != "loaded" && document.readyState != "complete" ) {
                setTimeout( arguments.callee, 0 );
                return;
            } else {
                // and execute any waiting functions
                isReady = true;
                eval(fn);
            }
        })();
    }

    // A fallback to window.onload that will always work
    addLoadEvent(fn);
}


/** sprintf not added yet, disabling for now
function vsprintf(tpl, arr) {

    if (typeof(arr) != 'object') { return ''; }
    if (tpl == '')               { return ''; }

    var i, e, n, v;
    n = new Array();

    // force an array
    for (i in arr) {  n.push('arr["' + i + '"]'); }
    v = n.join(", ");
    v = "sprintf(tpl, " + v + ");";
    return eval(v);
}
*/


/* set input check value,wanthome*/
function dic(v) {
    document.input_check.toggle.value=v;
    return true;
}

// set input check if route created
function dicr(v) {
    document.input_check.route.value=v;
    return true;
}

/***
 * WantHome Summary
 */
var wh = {

    /**
     * header sorting
     */
    sort: function (o) {
        document.summary_search_hidden.page_num.value = 1;
        document.summary_search_hidden.show_detail.value = 0;
        document.summary_search_hidden.order_by.value = o.ob;
        document.summary_search_hidden.asc_desc.value= o.ad;
        document.summary_search_hidden.submit();
        return;
    },

    /**
     * smaller call to toggle_all_radios function - pass through
     */
    tar: function (a,b,c) {
        toggle_all_radios(a,b,c); return false;
    },

    //cexit: function(page) {
    cexit: function(o) {

        var page = o.page;
        var msg = "";

        if (page == 'undefined') {
            page = 'summary page';
        }

        if (document.input_check != undefined) {
            if (document.input_check.toggle.value == 1) {

                if (o.action) {

                    switch (o.action) {

                        case 'edit':

                            if (o.post == 1) {
                                msg += 'You have unsaved changes! Your listing contains errors and has not been saved! Do you want to proceed and discard changes?';
                            } else {
                                msg += 'You have unsaved changes!  Do you want to proceed and discard your changes?';
                            }

                            break;

                        case 'add':

                            if (o.post == 1) {
                                msg += 'Your listing contains errors and has not been submitted! Do you want to proceed and discard your listing?';
                            } else {
                                msg += 'Your listing has not been submitted! Do you want to proceed and discard your listing?';
                            }
                            
                            break;
                    }

                } else {
                    //default
                    msg += 'You have unsaved changes!  Do you want to proceed and discard your changes?';
                }

                msg += '\n\n';
            }

            if (document.input_check.route.value == 1) {
                msg += 'You have started plotting a route. If you proceed, your ' +
                        'route information will be lost. Do you want to proceed and ' +
                        'discard your route?\n\n';
            }
        }

        if (msg != "") {

            msg += 'Click OK for yes, or Cancel to return to the ' + page + '.';

            if (!confirm(msg)) {
                return false;
            } else {
                return true;
            }
        }
        
        return true;
    },

    /**
     *  prompt user of unsaved changed upon leaving wh
     *
     * pn = page number
     */
    exit: function (o) {

        var msg = "";

        if (document.input_check != undefined) {
            if (document.input_check.toggle.value == 1) {
                msg += 'You have unsaved changes!  Do you want to proceed and ' +
                      'discard your changes?\n\n';
            }
        
            if (document.input_check.route.value == 1) {
                msg += 'You have started plotting a route. If you proceed, your ' +
                        'route information will be lost. Do you want to proceed and ' +
                        'discard your route?\n\n';
            }
        }

        if (msg != "") {

            msg += 'Click OK for yes, or Cancel to return to the ' + 'summary page' + '.';

            if (!confirm(msg)) {
                return false;
            }
        }

        if (o.what != null && o.what != undefined) {
            // Send user to view
            if (o.what != 'edit') {
                eval('document.summary_search_hidden.' + o.what + '.value=' + o.value);
                document.summary_search_hidden.submit();
                return false;
            }
        }

        return true;
    },

    /**
     * Help function to draw picture div
     */
    rbp_sp: function (event, json) {
        if (!rbp || rbp.loading_pd || !remote_ahrn_pic) {
            return false;
        }
        rbp.lc=rbp.get_coords(event);
        rbp.clear_anim_img_cache();
        rbp.loading_pd = true;
        remote_ahrn_pic.draw_pic_div(json);
        return false;
    }
}

/**
 * Returns the element object if it exists otherwise returns false
 */
function gid(element_id) {
    var f;
    f = document.getElementById(element_id);
    return (typeof(f) == 'undefined') ? false : f;
}

/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf () {
    var i = 0,
        a,
        f = arguments[i++],
        o = [],
        m,
        p,
        c,
        x;

    while (f) {
        if (m = /^[^\x25]+/.exec(f)) {
            o.push(m[0]);
        } else if (m = /^\x25{2}/.exec(f)) {
            o.push('%');
        } else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {

            if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");

            if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
                throw("Expecting number but found " + typeof(a));

            switch (m[7]) {
                case 'b': a = a.toString(2); break;
                case 'c': a = String.fromCharCode(a); break;
                case 'd': a = parseInt(a); break;
                case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
                case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
                case 'o': a = a.toString(8); break;
                case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
                case 'u': a = Math.abs(a); break;
                case 'x': a = a.toString(16); break;
                case 'X': a = a.toString(16).toUpperCase(); break;
            }

            a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
            c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
            x = m[5] - String(a).length;
            p = m[5] ? str_repeat(c, x) : '';
            o.push(m[4] ? a + p : p + a);

        } else throw ("Huh ?!");

        f = f.substring(m[0].length);
    }
    return o.join('');
}


function show_hocontact() {
    gid("hocontact").style.display="block";
    window.location.hash="hocontact_target";
}



var phone = {

    /***
     * confirm country change, if false, reset select list to original
     */
    toggle_country: function(o) {

        // check to see if any of the form fields have any values
        var ac = gid(o.field_name + '_area').value;
        var ln = gid(o.field_name + '_num').value;
        var ext = gid(o.field_name + '_ext');

        var validate = false;

        if (ac != "" || ln != "") {
            validate = true;
        }

        if (ext != null && ext.value != "") {
            validate = true;
        }

        if (validate) {
            if (confirm('You will need to re-enter your phone number if you change the country.\n\nClick OK to continue or Cancel to quit.')) {
                remote_utils.phone_change_fields(o);
            } else {

                e = gid(o.field_name + '_code');

                if (e) {

                    for (var i = 0; i <= e.options.length; i++) {
                        if (e.options[i].value == o.orig) {
                            e.selectedIndex = i;
                            return;
                        }
                    }
                }
            }
        } else {
            remote_utils.phone_change_fields(o);
        }
    }
}

var account_mgt = {

    /**
     * Helper function to process all changes when country is toggled between
     * OCONUS/CONUS on account_mgt.inc or complete_registration.inc pages
     *
     * input:
     *  cc = the country code
     *  pm_type = json string of selected property manager types
     */
    country_changed: function(o) {

        // store the selected country for downstream processing
        gid('country_code').value = o.cc;

        // Reset state drop with selected countries states
        remote_utils.refresh_state_options({'id':'company_state','country_code':o.cc});

        // toggle pm type options
        remote_pm.account_pm_type(o);


        // Reset the phone/fax fields if there is not a number
        if (gid('company_phone_area').value == "" && gid('company_phone_num').value == "" && gid('company_phone_ext').value == "") {

            // Reset company phone field
            remote_utils.phone_change_fields(
                                    {
                                    'field_name'    : 'company_phone',
                                    'type'          : 'phone',
                                    'cc'            : o.cc
                                    }
                                );
        }

        if (gid('company_fax_area').value == "" && gid('company_fax_num').value == "") {

            // reset company fax field
            remote_utils.phone_change_fields(
                                    {
                                    'field_name'    : 'company_fax',
                                    'type'          : 'fax',
                                    'cc'            : o.cc
                                    }
                                );
        }

        return;
    }
}


var custom_fields = {

    uk_valid_epc_score: function(v) {
        
        var good = false;
        var theNumber = parseInt(v);

        if (theNumber != 'NaN') {
            if (theNumber > 0 && theNumber <= 100) {
                good = true;
            }
        }

        if (!good) {
            alert('The EPC Score must be within 1 and 100');
            return false;
        } else {
            return true;
        }
    },

    /**
     * check all of the sections of the EPC Reference
     */
    uk_valid_epc_reference: function() {

        var i;
        var err = '';
        for (i = 1; i <= 5; i++) {
            var fld = gid('prop_custom_fld_3_' + i);
            if (isNaN(fld.value) || fld.value.length != 4) {
                if (err == '') {
                    err = 'The EPC Reference Number must be 20 digits long';
                }
            }
        }

        if (err) {
            alert(err);
            return false;
        }
        return true;
    }
}


function get_selected_value(id) {
    if (id == null) { alert('mising id'); }

    var elem = gid(id);
    if (elem != null) {
        return elem.options[elem.selectedIndex].value;
    } else {
        return false;
    }

}

/* toggle grade amounts
 * turn them on or off to follow BAH checkmark
*/
var old_vals = new Array();     // var to hold original values of boxes
function t_ga(rows) {

    var f;
    var i;
    var f_bah = document.getElementById('f_use_bah');
    if (!f_bah) { return false; }
    var dis = f_bah.checked;

    for (i = 0; i < rows; i++) {
        f = document.getElementById('f_price_' + i + '_');
        if (f) { 
            f.disabled = dis; 
            f.style.background = (dis) ? '#B9C8D6' : '#FFFFFF'; 
            if (f.disabled) { 
                old_vals[i] = f.value; 
                f.value = ''; 
            } else {
                f.value = old_vals[i];
            }
        }
    }

}

