var AutoLogin = 0;
function initMenu() {
  var dom = top.document.domain;
  var dchk = dom.split(/\./);
  if (dchk[0] == 10 && dchk[1] == 4 && dchk[2] == 1) {
    window.status = "Development Environment - Auto Login Enabled";
    var lparm = parent.document.location.href.split(/\?/);
    if (lparm.length > 1) {
      parentFile = lparm[0].split(/\//);
      pn = parentFile[parentFile.length-1].split(/\./);
      var parentName = pn[0];
      lparm = lparm[1].split(/\&/);    
      window.status = "Set Development Parms:"; for (var l = 0; l < lparm.length; l++) { var parms = lparm[l].split(/=/); try { window.status += " "+parms[0]+" = "+parms[1]; eval("var "+parms[0]+" = '"+parms[1]+"';"); } catch (e) { alert("Unable to Set P["+parms[0]+"] - | V["+parms[1]+"]"); }  }
      if (typeof UPass != undefined) { rlogin.UPass.value = UPass; }
      if (typeof UserID != undefined) { rlogin.UserID.value = UserID; }
      if (rlogin.UPass.value != '' && rlogin.UserID.value != '') { AutoLogin = 1; }
    }      
  }
  if (top.menus) {
    CreateMenu(1);
    if (AutoLogin==1) {
      dologin();
    }
  } else {
    window.setTimeout("initMenu()",50);
  }
}

function reAuth (){
  PauseApp();
  var thtml = "<table cellspacing=0 cellpadding=0 style='margin:20px;'><form name=ReAuthForm>";
  thtml += "<tr><td colspan=2><b style='font-size:12px;'>You have been logged on to the application for an extended period of time.  Please re-enter your user information.</b></td></tr>";
  thtml += "<tr height=20><td></td></tr>";
  thtml += "<tr><td align=right>LoginID:</td><td><input type=text name=LoginID size=25 onkeydown='if(event.keyCode == 13){ eval(topMBX).menu.doreAuth(); }else{ event.cancelBubble=true;event.returnValue=true; }'></td></tr>";
  thtml += "<tr><td align=right>Password:</td><td><input name=Password type=password size=25 onkeydown='if(event.keyCode == 13){ eval(topMBX).menu.doreAuth(); }else{ event.cancelBubble=true;event.returnValue=true; }'></td></tr>";
  thtml += "<tr height=20><td></td></tr>";
  thtml += "<tr><td colspan=2 align=center><a href=# onclick='eval(topMBX).menu.doreAuth();' class=s_button>Submit</a></td></tr>";
  thtml += "<tr><td colspan=2><span id=RAFMsg style='font-size:12px;color:red;'></span></td></tr>";
  thtml += "</form></table>";
  ShowSysMessage("Re-Authorization Required",thtml,null,null,1); // <-------------change this to a 1 to hide the close button
}

function doreAuth (){
  if(event){ event.cancelBubble=true; }
  var rLogin = eval(topMBX).main.ReAuthForm.LoginID.value;
  var rPassword = eval(topMBX).main.ReAuthForm.Password.value;
  if(rLogin == "" || rPassword == ""){ alert("Please enter both a username and password"); return false; }
  var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.Open("POST", "https://"+document.location.host+"/cgi-bin/login/reauth.cgi", false);
  xmlhttp.setRequestHeader("Cache-Control", "no-cache");
  xmlhttp.setRequestHeader("Authorization", "Basic "+encodeBase64(rLogin+":"+rPassword));
  xmlhttp.Send();
  if (xmlhttp.responseText.match(/\<HTML\>/) || xmlhttp.responseText.match(/\<html\>/)) {
    eval(topMBX).LoginID = ""; eval(topMBX).Password = ""; rPassword = "";
    if (xmlhttp.responseText.match(/HTTP 401 Authentication Error/)) {
      top.main.RAFMsg.innerHTML = "<br>We are sorry but that username and / or password does not match our records. Please try again.";
    } else {
      top.main.RAFMsg.innerHTML = "<br>We are sorry but there was an error logging you on. Please try again in a few minutes.";  
    }
  } else {    
    eval(xmlhttp.responseText);    
    HideSysMessage();
    PlayApp();
  }
  delete xmlhttp;
  return true;
}

function PauseApp(){  
  if(typeof eval(topMBX).menu.cmd != 'undefined'){ eval(topMBX).menu.MBXConnRequestStop(); }
  if(typeof eval(topMBX).cmd != 'undefined'){ eval(topMBX).MBXConnRequestStop(); }  
}
function PlayApp(){
  if(typeof eval(topMBX).menu.cmd != 'undefined'){ eval(topMBX).menu.MBXConnRequestStart(); }
  if(typeof eval(topMBX).cmd != 'undefined'){ eval(topMBX).MBXConnRequestStart(); }  
}

function ToggleApp(wmenu) {
  //Send Login Info to App Server with SessionID so SessionIDs will match
  var sUser = top.LoginID; var sPWD = top.Password; var ok = 0;
  if (top.MBXServer[wmenu].loggedin != "0") { ok = 1; } else { if (dologin(wmenu)) { ok = 1; top.MBXServer[wmenu].loggedin = "0"; } } //Change to 1 when caching is working
  if (ok == 1) {
    parent.CurrentApp = wmenu;
    for (var n in top.menus) { menul = eval("AppServer"+n).length; for (var i = 0; i<menul; i++) { if (n == wmenu) { eval("AppServer"+n)[i].style.display='inline'; } else { if (n != 'nohide') { eval("AppServer"+n)[i].style.display='none'; } } } }
  } else {
    top.LoginID = sUser; top.Password = sPWD;
  }
  if (event) { event.returnValue = false; }
}
function Toggle(wmenu) {
  if (top.is_ie || top.is_aol5 || top.is_aol6) {
    for (var n in top.menus[parent.CurrentApp]) { menul = eval("d"+n).length; for (var i = 0; i<menul; i++) { if (n == wmenu) { eval("d"+n)[i].style.display='inline'; } else { if (n != 'nohide') { eval("d"+n)[i].style.display='none'; } } } }
    if (top.UType == 'V' || top.UType == 'A'){
      if(wmenu == 'nada'){stayOpen = 1;}
      else{stayOpen = 0;}
    }
  } else {
    var h2s = document.getElementsByTagName("DIV"); for (var i = 0; i < h2s.length; i++) { if (h2s[i].id == "d"+wmenu) { h2s[i].style.display='inline'; } else { if (h2s[i].id != 'nohide') { h2s[i].style.display='none'; } } }
  }
  userlist.style.pixelHeight = document.body.offsetHeight-themenu.offsetHeight-98-duserlist.offsetTop; //-115
  userlist.style.setExpression("height","document.body.offsetHeight-themenu.offsetHeight-98-duserlist.offsetTop");
}
function ExecCommand(cid,mcmd) {
  if (top.UType == 'A') {
    if (!mcmd) { ccmd=prompt("Enter Command to Execute:"); } else {ccmd = mcmd; }
    top.WebSubmit(top.UType,"ExecCommand","<input type=text name=UserID value="+cid+"><input name=CMD value="+top.derefit(ccmd)+">","menu","ExecutedCMD",'s','ClientServer');
  } else {
    alert("Only Administrators can do that!");
  }
  if (event) { event.returnValue = false; }
}
function ExecutedCMD(ret,msg) {
  top.SubmitResult(1);top.SetWait(0);
  if (!ret) {
    alert("Error:"+msg);
  }
}
function ForcedSave(cid) {
  top.WebSubmit(top.UType,"ForcedSave","<input type=text name=UserID value="+cid+">","menu","ForcedSaveOK",'y','ClientServer');
  if (event) { event.returnValue = false; }
}
function ForcedSaveOK(ret,msg) {
  top.SubmitResult(1);top.SetWait(0);
  if (!ret) {
    alert("Error:"+msg);
  }
}

function get_cookie ( cookie_name ) {
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );

  if ( results )
    return ( results[1] );
  else
    return undefined;
}

function dologin() {
  var AppCookie = "";
  logout = 0; 
  var rLogin = rlogin.UserID.value; 
  var rPassword = rlogin.UPass.value;
  if (!top.is_ok) { alert("The EML website works best with Microsoft Internet Explorer 6.0, if you experience any problems please visit our Product support link under BPO Services for help."); }
  if (event) { event.returnValue = false; }
  if (rLogin != "") {    
    var _cookie_string = get_cookie("SessionID"); 
    if (_cookie_string && _cookie_string != "X,X") {
      var _session_info  = _cookie_string.split(",");
      var _session_login = _session_info[0];
      if (rLogin.toUpperCase() != _session_login.toUpperCase()) {
        alert("you are only allowed to login as "+_session_login+". You entered "+rLogin+". If you want to login as a different user please start a new IE window.");
        return;
      }
    }
    if (top.banner.dlogout.style.display=='none') { top.banner.dlogout.style.display='inline'; }
    if (top.menu.dlogout.style.display=='none') { top.menu.dlogout.style.display='inline'; }
    try {
      document.cookie = "SessionID=X,X";
   // cannot use this while using AUTHREQUIRED as it uses basic auth - out purpose here is to make sure we dont get cached credentials
   // xmlhttp = new XMLHttpRequest();
      var xmlhttp; 
      try {
        xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");              
      } catch (e) {
        try {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
          alert("No Support for xmlhttp");
        }
      }
      xmlhttp.Open("POST", "https://"+document.location.host+"/cgi-bin/login/login.cgi", false);
      xmlhttp.setRequestHeader("Authorization", "Basic "+encodeBase64(rLogin+":"+rPassword));
      xmlhttp.Send();
      if (xmlhttp.responseText.match(/\<HTML\>/i)) {
        //top.main.ShowModal("Login Error",xmlhttp.responseText,null,1);
        top.LoginID = ""; top.Password = ""; rPassword = "";
        if(_cookie_string) {document.cookie = "SessionID="+_cookie_string;}
        ShowSysMessage("Server Authentication Failure",xmlhttp.responseText,"");
        if (top.banner.dlogout.style.display=='inline') { top.banner.dlogout.style.display='none'; }
        if (top.menu.dlogout.style.display=='inline') { top.menu.dlogout.style.display='none'; }        
      } else {
        document.cookie=document.cookie;//WARNING: do not delete this line. I know it looks like it shold not do anything, but is necessary to get the cookies working like IE7 in IE8. EH - 10/10/08
        eval(xmlhttp.responseText);
        prelogin.innerHTML = "<a href='javascript:Toggle(\"nada\");' title='Minimize the Menu' style='position:absolute;top:3px;left:6px;'><div class='login_btn_up'></div> <a class='mitem' href='market/loginhelp.html' target=main style='position:absolute;top:1px;left:23px;'>Click Here for Help!</a>"; 
      }
      delete(xmlhttp);
    } catch (e) {      
      rlogin.action="https://"+document.location.host+"/cgi-bin/login/login.cgi";
      top.LoginID = ""; top.Password = "";
      rlogin.target="main";
      rlogin.submit();
    }
  }
}
var wOut;
var wIn;
var wInit = 1;
var logout = 0;
var stayOpen = 1;
var tUserRefresh_wait = 120000;
function LogOff(oldUtype) {
  window.clearTimeout(t_UserRefresh);
  window.clearTimeout(t_Chat);
  WebSubmit(oldUtype,"LogOff","<input type=text name=SessionID value="+top.SessionID+">","menu","LoggedOff",'s','ClientServer');
}
function LoggedOff(){
  //document.cookie = "SessionID=X,X";
  top.document.location.href='https://'+document.location.host;
}
var tst = 0;
function CheckNext() {
  tst = 1;
}
function ShowUserMiniMenu(cid) {
  if (!cid || (top.UType != 'A' && top.UType != 'V')) { return true; }
  var ReadOnly=1;
  if(top.UType=='A') {
    ReadOnly=0;
  } else {
    for(var i=0; i<top.OptObj.EmpRoles.b.length; i++) {
      if(top.OptObj.EmpRoles.b[i] == top.OptObj.User.ContactID)  ReadOnly=0;
    }
  }
  d_MiniMenu.cid = cid;
  d_MiniMenu.ReadOnlyBrokerSearch = ReadOnly;
  d_MiniMenu.style.pixelLeft = event.srcElement.offsetLeft + 9;
  d_MiniMenu.style.pixelTop = event.srcElement.offsetTop + duserlist.offsetTop - userlist.scrollTop + themenu.offsetHeight + 36;
  d_MiniMenu.style.visibility='visible';
  event.returnValue=false;
  event.cancelBubble=true;
  return false;
}
function ShowMenu(todo) {
   if (!wInit) {
    if (top.UType == 'V' || top.UType == 'A') {
      if (todo || stayOpen) {
        wIn = window.setTimeout("top.menuframe.cols='151,*';",180);
        window.clearTimeout(wOut);
      } else {
          wOut = window.setTimeout("top.menuframe.cols='4,*';",600);
          window.clearTimeout(wIn);
      }
    }
  }
}
var t_UserRefresh;
var t_UserRefreshFlag = -1; //-1 is login, should update the users. Then set to zero and gray out user list on next GetOnlineUsers response from server
function ShowUsers(ret) {
  if (ret) { SubmitResult(1);SetWait(0); }
  if(top.UType != 'V' || t_UserRefreshFlag == -1){
    userlist.style.filter = '';    
    userlist.style.backgroundColor = '';
    if(top.menu.dRefreshButton){ top.menu.dRefreshButton.style.visibility = 'hidden'; }      
    t_UserRefreshFlag = 0;
    duserlist.style.display = 'inline';
    var tmp ="";
    var lObj = top.Users; var cnt = 0;
    var ugrp; var re = /\'/g;
    var aObj={}; var vObj={}; var cObj={}; var bObj={}; var pObj={}; var other={};
    var aCnt=-1; var vCnt=-1; var cCnt=-1; var bCnt=-1; var pCnt=-1; var cother=-1;
    var qcnt = -1;
    for (var i in lObj) {
      qcnt++;
      try {
        switch(lObj[i]['UserType']) {
          case 'A'  : aCnt++; aObj[aCnt]=lObj[i]; break;
          case 'V'  : vCnt++; vObj[vCnt]=lObj[i]; break;
          case 'C'  : cCnt++; cObj[cCnt]=lObj[i]; break;
          case 'B'  : bCnt++; bObj[bCnt]=lObj[i]; break;
          case 'P'  : pCnt++; pObj[pCnt]=lObj[i]; break;
          default   : cother++; other[cother]=lObj[i]; break;
        }
      } catch(e) {alert(qcnt+"\n"+i+"\n"+e.description+"\n"+GetTextFromObject(lObj[i]));}
    }
    if(qcnt > 1) {
      qcnt=0;
      if(cother>=0) {
        for(var i in other) { lObj[qcnt++] = other[i]; }
      }
      if(aCnt>=0) {
        _QuickSort(aObj, 0, aCnt, 'UserName', _QuickSort_default, 1);
        for(var i in aObj) { lObj[qcnt++] = aObj[i]; }
      }
      if(vCnt>=0) {
        _QuickSort(vObj, 0, vCnt, 'UserName', _QuickSort_default, 1);
        for(var i in vObj) { lObj[qcnt++] = vObj[i]; }
      }
      if(cCnt>=0) {
        _QuickSort(cObj, 0, cCnt, 'UserName', _QuickSort_default, 1);
        for(var i in cObj) { lObj[qcnt++] = cObj[i]; }
      }
      if(pCnt>=0) {
        _QuickSort(pObj, 0, pCnt, 'UserName', _QuickSort_default, 1);
        for(var i in pObj) { lObj[qcnt++] = pObj[i]; }
      }
      if(bCnt>=0) {
        _QuickSort(bObj, 0, bCnt, 'UserName', _QuickSort_default, 1);
        for(var i in bObj) { lObj[qcnt++] = bObj[i]; }
      }

    }
    for (var i in lObj) {
      cnt++;
      if (cnt > 1) {
        if (cnt == 2) { ugrp = lObj[i]['UserType']; }
        if (ugrp != lObj[i]['UserType']) { tmp += "<div style='line-height:2px;border-bottom:1px solid #CCCCCC;margin:1px;margin-left:2px;margin-right:2px;'></div>";ugrp = lObj[i]['UserType']; }
        var msgs = "<b style=padding:5px>&nbsp;</b>";
        var stat = ""; var status="";
        if (lObj[i]['Status'] == 'P') { stat = "color:#"+top.tStyle.colors.d_menu_chat_P+";"; }
        if (lObj[i]['Status'] == 'F') { stat = "color:#"+top.tStyle.colors.d_menu_chat_F+";"; }
        if (lObj[i]['Status'] == 'O') { stat = "color:#"+top.tStyle.colors.d_menu_chat_O+";"; }//online -  blue
        if (lObj[i]['Status'] == 'B') { stat = "color:#"+top.tStyle.colors.d_menu_chat_B+";";status = "Busy: "; }//busy -  blue
        if (lObj[i]['Status'] == 'U') { stat = "color:#"+top.tStyle.colors.d_menu_chat_U+";"; }//signed off - lt grey
        if (lObj[i]['Status'] == 'I' && lObj[i]['Messages'] > 0) { stat = "color:#"+top.tStyle.colors.d_menu_chat_U+";"; }
        if (lObj[i]['Status'] == 'I' && lObj[i]['Messages'] == 0 && (top.UType=='V' || top.UType=='A') ) { stat = "color:#"+top.tStyle.colors.d_menu_chat_I+";"; }//invisible no messages vendor or admin
        if (lObj[i]['Status'] == ''  && lObj[i]['Messages'] > 0) { stat = "color:#"+top.tStyle.colors.d_menu_chat_U+";"; }//signed off - lt grey
        if (lObj[i]['Messages'] > 0) { msgs = "<a class='chat' href=# onclick='GetMessages("+lObj[i]['UserID']+",\""+lObj[i]['UserName']+"\")'><b style=padding:2px;color:#FF0000;>"+lObj[i]['Messages']+"</b>&nbsp;</a>"; }
        if(stat != "" && lObj[i]['Status'] != 'P'){
          tmp += "<nobr>&nbsp;"+msgs+"<a href='#' class='chat' oncontextmenu=\"ShowUserMiniMenu('"+lObj[i]['UserID']+"')\" onclick=\"GetMessages("+lObj[i]['UserID']+",'"+lObj[i]['UserName'].replace(re, "\\\'")+"',1)\" style='"+stat+"'>"+"&nbsp;"+status+lObj[i]['UserName']+"</a></nobr><br>";
        }else if(stat != ""){
          tmp += "<nobr>&nbsp;"+msgs+"<a href='#' class='chat' oncontextmenu=\"return false;\" onclick=\"return false;\" style='"+stat+"'>"+"&nbsp;"+lObj[i]['UserName']+"</a></nobr><br>";
        }
      }
    }
    userlist.innerHTML = tmp;
  } else {    
    userlist.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=5)';    
    userlist.style.backgroundColor = '#f0ebe6';
    if(!top.menu.dRefreshButton){
      refreshButton = "<div id=dRefreshButton style='position:absolute;top:75px;left:expression(document.body.offsetWidth-115);width:70px;height:70px;filter:none;'><a id=drefreshusers href=# class=s_button onclick='top.menu.t_UserRefreshFlag = -1;top.menu.GetOnlineUsers();' style='font-size:15px' title='Refresh user list'>Refresh</a></div>"
      top.menu.duserlist.insertAdjacentHTML("beforeEnd",refreshButton);
    } else {
      top.menu.dRefreshButton.style.visibility = 'visible';
    }    
  }
  if(getOnlineUsers) {
    t_UserRefresh = window.setTimeout("GetOnlineUsers()",tUserRefresh_wait);
  }
}
function _QuickSort(vec, lo, hi, col, fnc, dir) {
  var pivot, loSwap, hiSwap, temp;
  if (hi - lo == 1)  {
    if (fnc(vec[lo][col],vec[hi][col],dir) == 1) { temp = vec[lo]; vec[lo] = vec[hi];  vec[hi] = temp;  }
    return;
  }
  pivot = vec[parseInt((lo + hi) / 2)];
  vec[parseInt((lo + hi) / 2)] = vec[lo];
  vec[lo] = pivot; loSwap = lo + 1; hiSwap = hi;
  try{
    do {
      while (loSwap <= hiSwap && (fnc(vec[loSwap][col],pivot[col],dir) == 0 || fnc(vec[loSwap][col],pivot[col],dir) == -1)) loSwap++;
      while (fnc(vec[hiSwap][col],pivot[col],dir) == 1 )      hiSwap--;
      if (loSwap < hiSwap) { temp = vec[loSwap]; vec[loSwap] = vec[hiSwap];   vec[hiSwap] = temp;     }
    } while (loSwap < hiSwap);
  }catch(e){return;}
  vec[lo] = vec[hiSwap]; vec[hiSwap] = pivot;
  if (lo < hiSwap - 1)    _QuickSort(vec, lo, hiSwap - 1, col, fnc, dir);
  if (hiSwap + 1 < hi)    try{_QuickSort(vec, hiSwap + 1, hi, col, fnc, dir);}catch(e){}
  //try{if (hiSwap + 1 < hi)  QuickSort(vec, hiSwap + 1, hi, col, fnc, dir); } catch(e) { }
}
function _QuickSort_default (a, b, dir) {
  return (a == b) ? 0 : (a > b) ? 1*dir : -1*dir;
}

var getOnlineUsers=1;
function GetOnlineUsers() {
  window.clearTimeout(t_UserRefresh);
  if(getOnlineUsers) {
    WebSubmit(top.UType,"GetOnlineUsers","<input name=SessionID value="+top.SessionID+">","menu","ShowUsers",'s','ClientServer');
  }
}
var con_cnt = 0;
function SendMessage(id,msg) {
  con_cnt++;
  var tD = new Date();
  var thedate = (tD.getMonth()+1)+"/"+tD.getDate()+"/"+tD.getFullYear();
  var hrs = tD.getHours();
  var ampm = "AM"; if (hrs > 12) { ampm = "PM"; hrs=hrs-12; }
  var mins = tD.getMinutes();
  if(mins<10) mins = '0'+mins.toString();
  var thetime = hrs+":"+mins+ampm;
  WebSubmit(top.UType,"SendMessage","<input name=ContactID value="+id+"><textarea name='MsgTxt' value=''>"+top.derefit(msg)+"</textarea>","menu","SentMessage",'s','ClientServer');
  try {
    top.main.MsgTxt.innerHTML += "<div id=ConMarker"+con_cnt+" class='s_msg_sent'><table cellpadding=0 cellspacing=0 style='width:412;'><tr><td style='width:94' valign=top><a href='#' class='s_msg_link_d' onclick='ConMarker"+con_cnt+".outerHTML=\"\";'>Del</a>&nbsp;<span style='margin-left:2px;margin-right:6px;'>Sent</span>"+thetime+"</td><td style='padding-left:3px;'><span id=MessageTxt from='"+top.OptObj.Employees[top.ContactID]+"'>"+safit(top.main.MsgToSend.value)+"</span></td></tr></table></div>";
    top.main.MsgToSend.value = "";
    top.main.MsgTxt.scrollTop = top.main.MsgTxt.scrollHeight-top.main.MsgTxt.offsetHeight+2;
  } catch(e) { }
}
function SentMessage() {
  //window.status = 'Message Sent!';
  SubmitResult(1);SetWait(0);
}
function ForwardMessages() {
  if(typeof parent.main.MessageTxt!='undefined') {
    now = new Date();
    var allText = '';
    if(typeof parent.main.MessageTxt.length!='undefined') {
      for(i=0; i<parent.main.MessageTxt.length; i++) {
        allText += parent.main.MessageTxt[i].from+": "+parent.main.MessageTxt[i].innerText+"\n";
      }
    } else {
      allText = parent.main.MessageTxt.from+": "+parent.main.MessageTxt.innerText+"\n";
    }
    var mailURL = "mailto:?subject=" + escape("Chat From "+parent.main.MsgSrc.innerText+" on "+now.toLocaleString()) + "&body="+escape(allText);
    if(mailURL.length>2000) mailURL=mailURL.toString().substr(0, 2000);
    top.location.href=mailURL;
  } else alert('No messages to send!');
}
function AddMessagesToNotes() {
  if(!parent.main.dSaveMessages) {
    var tmp  = "<div id=dSaveMessages style='display:none;'><div class='opaque_bg' style='z-index:10000000;'></div>";
        tmp += "<div id=d_SaveMessages class='s_msg_dialog' style='width:220;height:110;word-wrap:break-word;padding:1px;z-index:10000001;position:absolute;top:expression(document.body.offsetHeight/2-(d_SaveMessages.offsetHeight/2));left:expression(document.body.offsetWidth/2-(d_SaveMessages.offsetWidth/2));'>";
        tmp += "  <div class='s_msg_hdr'><nobr>Add Messages to Notes</nobr></div>";
        tmp += "  <div class='s_msg_txt' style='width:100%;height:100%;'>";
        tmp += "    <form name=SaveMessagesForm>";
        tmp += "      <input type=hidden name=vContactID always=1><input type=hidden name=bContactID always=1><input type=hidden name='SaveMessages' always=1 value='bn'>";
        tmp += "      <div style='font-weight:bold;padding-left:5px;'>Add Conversation To:</div>";
        tmp += "      <a id=bnLink href=# class='s_msg_link_d' style='font-weight:normal;padding-left:10px;' onclick='parent.menu.SaveMessagesChange(\"bn\");'>Broker Notes</a><br>";
        tmp += "      <a id=onLink href=# class='s_msg_link_d' style='font-weight:normal;padding-left:10px;' onclick='parent.menu.SaveMessagesChange(\"on\");'>Order Notes</a><br>";
        tmp += "      <a id=vcLink href=# class='s_msg_link_d' style='font-weight:normal;padding-left:10px;' onclick='parent.menu.SaveMessagesChange(\"vc\");'>Vendor Comments</a><br>";
        tmp += "      <a id=bcLink href=# class='s_msg_link_d' style='font-weight:normal;padding-left:10px;' onclick='parent.menu.SaveMessagesChange(\"bc\");'>Broker Comments</a><br>";
        if (typeof top.SysSettings != 'undefined' && top.SysSettings.ServerID==5) { 
          tmp += "      <div style='padding-left:10px;height:36px;'>";
          tmp += "        <span id=dOrderID style='display:inline;'>Order ID: <input onkeypress='if(event.keyCode == 13) {parent.menu.SaveMessages();event.returnValue=false;}' type=text name=OrderID></span><br>";
          tmp += "        <span id=dInternalOnly style='display:none;'>Internal Only: <input type=checkbox name=InternalOnly></span>";
        } else {
          tmp += "      <div style='padding-left:10px;height:18px;'>";
          tmp += "        <span id=dOrderID style='display:inline;'>Order ID: <input onkeypress='if(event.keyCode == 13) {parent.menu.SaveMessages();event.returnValue=false;}' type=text name=OrderID></span>";
        }
        tmp += "      </div>";
        tmp += "    </form>";
        tmp += "  </div>";
        tmp += "  <div class='s_msg_txt' style='text-align:center;'>"
        tmp += "    <a href=# class='s_msg_link_d' onclick='parent.menu.SaveMessages();'>SAVE</a>";
        tmp += "  </div>";
        tmp += "  <div id='dCloseAddMessages' style='position:absolute;top:2;left:206;'><a href=# class='s_msg_link' onclick='top.menu.CloseAddMessages();' title='Close'>X</a></div>";
        tmp += "</div></div>";
    parent.main.document.body.insertAdjacentHTML("beforeEnd",tmp);
    parent.OptObj.SaveMessages = {  'bn':'Broker Notes',
                                    'on':'Order Notes',
                                    'vc':'Vendor Comments',
                                    'bc':'Broker Comments' };
  }
  parent.main.SaveMessagesForm.vContactID.value=top.ContactID;
  parent.main.SaveMessagesForm.bContactID.value=curContactID;
  parent.main.SaveMessagesForm.OrderID.value='';
  parent.main.dSaveMessages.style.display='inline';
  parent.main.bnLink.click();
}
function SaveMessagesChange(newVal) {
  if (typeof top.SysSettings != 'undefined' && top.SysSettings.ServerID==5) { 
    switch(newVal) {
      case 'bn':  top.main.SaveMessagesForm.InternalOnly.checked = false; top.main.dInternalOnly.style.display='none'; top.main.dOrderID.style.display='none'; top.main.SaveMessagesForm.OrderID.disabled=true; break;
      case 'on':  top.main.dInternalOnly.style.display='inline'; top.main.dOrderID.style.display='inline'; top.main.SaveMessagesForm.OrderID.disabled=false; break;
      default:    top.main.SaveMessagesForm.InternalOnly.checked = false; top.main.dInternalOnly.style.display='none'; top.main.dOrderID.style.display='inline'; top.main.SaveMessagesForm.OrderID.disabled=false;
    }
  } else {
    switch(newVal) {
      case 'bn':  top.main.dOrderID.style.display='none'; top.main.SaveMessagesForm.OrderID.disabled=true; break;
      default:    top.main.dOrderID.style.display='inline'; top.main.SaveMessagesForm.OrderID.disabled=false;
    }
  }
  parent.main.SaveMessagesForm.SaveMessages.value=newVal;
  for(i in parent.OptObj.SaveMessages) {
    obj=eval('parent.main.'+i+'Link');
    if(i==newVal) {
      obj.style.fontWeight='bold';
    } else {
      obj.style.fontWeight='normal';
    }
  }
}
function SaveMessages() {
  thtml  = "<input type=hidden name=vContactID value="+top.ContactID+">";
  thtml += "<input type=hidden name=bContactID value="+curContactID+">";
  thtml += "<input type=hidden name=SaveMessages value="+parent.main.SaveMessagesForm.SaveMessages.value+">";
  if(!(parent.main.SaveMessagesForm.OrderID.disabled)) {
    if(parent.main.SaveMessagesForm.OrderID.value=='') {
      alert('You MUST enter an Order ID to add these messages to the '+parent.OptObj.SaveMessages[parent.main.SaveMessagesForm.SaveMessages.value]+'!');
      parent.main.SaveMessagesForm.OrderID.focus();
      return;
    }
    thtml += "<input type=hidden name=OrderID value="+parent.main.SaveMessagesForm.OrderID.value+">";
  }
  if (typeof top.SysSettings != 'undefined' && top.SysSettings.ServerID==5) { 
    if(parent.main.SaveMessagesForm.InternalOnly.checked) {
      thtml += "<input type=hidden name=InternalOnly value=1>";
    }
  }
  allText='';
  if(typeof parent.main.MessageTxt.length!='undefined')
    for(i=0; i<top.main.MessageTxt.length; i++) allText += top.main.MessageTxt[i].from+": "+safit(top.main.MessageTxt[i].innerHTML)+"<br>";
  else allText = top.main.MessageTxt.from+": "+safit(top.main.MessageTxt.innerHTML)+"\n";
  thtml += "<textarea name='Messages'>"+allText+"</textarea>";
  top.WebSubmit(top.UType, 'AddMessagesToNotes', thtml, 'menu', 'SavedMessages', 'a', 'ClientServer');
  if(event) { event.returnValue='false'; }
}
function CloseAddMessages() {
  top.main.dSaveMessages.style.display='none';
  return 1;
}
function SavedMessages(ret) {
  if(ret==0) {
    CloseAddMessages();
  }
  top.SubmitResult(1);top.SetWait(0);
  if(event) { event.returnValue='false'; }
}

var curMessageSrc;
var curContactID;
var t_Chat;
var curChange=0;
function GetMessages(ContactID,MessageSrc,shownew) {
  try {
    if (!shownew && top.main.dMessages.style.display == 'none') {
    } else {
      window.clearTimeout(t_Chat);
      if (MessageSrc) { curMessageSrc = MessageSrc; }
      if (ContactID) { curContactID = ContactID; curChange=1; Shown = {}; }
      if (!top.main.dMessages) {
        var tmp  = "<div id=dMessages style='display:none;'><div class='opaque_bg'></div>";
            if(top.UType == 'V' || top.UType == 'A') {
               tmp += "<div class='s_msg_dialog' style='word-wrap:break-word;padding:1px;z-index:9999999;position:absolute;top:expression(document.body.offsetHeight/2-110);left:expression(document.body.offsetWidth/2-220);width:440;height:230;'>";
               tmp += "  <div class='s_msg_hdr'><nobr><span id=MsgHdr></span>&nbsp;<span id=MsgSrc></span>&nbsp;<span id=MsgState></span><br><span id=MsgCompany>&nbsp;</span></div>";
            } else {
               tmp += "<div class='s_msg_dialog' style='word-wrap:break-word;padding:1px;z-index:9999999;position:absolute;top:expression(document.body.offsetHeight/2-110);left:expression(document.body.offsetWidth/2-220);width:440;height:220;'>";
               tmp += "  <div class='s_msg_hdr'><nobr><span id=MsgHdr></span>&nbsp;<span id=MsgSrc></span>&nbsp;<span id=MsgState></span></div>";
            }
            tmp += "  <div id=MsgTxt class='s_msg_txt' style='overflow-y:auto;width:436;height:161;'></div>";
            if(top.UType=='V'){
              tmp += "  <div class='s_msg_txt' style='width:436;height:18;overflow-y:hidden;text-align:center;'><a href=# class='s_msg_link_d' onclick=top.menu.ForwardMessages()>Forward All</a><span style='width:150px;'>&nbsp;</span><a href=# class='s_msg_link_d' onclick=top.menu.AddMessagesToNotes()>Add To Notes</a></div>";
            }
            tmp += "  <div class='s_msg_snd' style='background-color:#F3F3F3;'><textarea onkeypress='if (event.keyCode == 13) { top.menu.SendMessage(top.menu.curContactID,this.value);event.returnValue=false;}' id=MsgToSend style='background-color:#F0F0F0;width:384;margin-right:5px;overflow-y:auto;'></textarea>&nbsp;<a href='#' class='s_msg_link_d' onclick='top.menu.SendMessage(top.menu.curContactID,MsgToSend.value);'>Send</a></div>";
            tmp += "<div style='position:absolute;top:2;left:360;'><a class='s_msg_link' href='#' onclick='top.menu.ClearMessages();' title='Clear Chat'>Clear Chat</a>&nbsp;&nbsp;<a href=# class='s_msg_link' onclick='top.menu.CloseMessages();' title='Close'>X</a></div>";
            tmp += "</div></div>";
        top.main.document.body.insertAdjacentHTML("beforeEnd",tmp);
      }
      WebSubmit(top.UType,'GetMessages','<input name=ContactID value='+curContactID+'>','menu','GotMessages','s','ClientServer');
      t_Chat = window.setTimeout("GetMessages();",8000);
      
      // Checks to see if user is currently viewing a pdf. If so, hide the pdf window so that the chat window can be seen. This is the only way I found to accomplish this. -- rak 10/19/2007
      if(typeof(top.main.iORD) == "object" && typeof(top.main.iORD.iFileMan) == "object" && top.main.iORD.iFileMan.fileType == "p"){
        top.main.iShowFile.document.body.style.display = "none";
      }
    }
  } catch(e) { 
    if (top.debug) {
      alert('Caught error in GetMessages: ' +e);
    }
    return 1; 
  }
}
function CloseMessages() {
  top.main.dMessages.style.display = 'none';
  window.clearTimeout(t_Chat);
  
  // Checks to see if user is viewing a pdf behind the chat window. If so, make the pdf display again after closing the chat window. -- rak 10/19/2007
  if(typeof(top.main.iORD) == "object" && typeof(top.main.iORD.iFileMan) == "object" && top.main.iORD.iFileMan.fileType == "p"){
    top.main.iShowFile.document.body.style.display = "inline";
  }  

}
function donada() {
  if (event) { event.returnValue = false; event.cancelBubble = true; }
}
function ClearMessages() {
  window.clearTimeout(t_Chat);
  var sms = "";
  var first=1;
  for (var i in Shown) {
    if (first==1) { first=0; } else { sms += ","; }
    sms += i;
  }
  WebSubmit(top.UType,'MarkMessage','<input name=MessageID value='+sms+'><input name=ContactID value='+curContactID+'>','menu','GotMessages','s','ClientServer');
  top.main.MsgTxt.innerHTML = "";
  t_Chat = window.setTimeout("GetMessages();",8000);
}
var listObj;
function GotMessages() {
  top.main.MsgHdr.innerText = "Your Conversation with";
  top.main.MsgSrc.innerText = curMessageSrc;
  if (top.sourceCompany != "" && (top.UType == 'V' || top.UType == 'A')) {
      top.main.MsgCompany.innerText = '[' + top.sourceCompany + ']';
  }
  if(top.sourceState != "") {top.main.MsgState.innerText = " - " + top.sourceState;} else {top.main.MsgState.innerText = "";}
  SubmitResult(1);SetWait(0);
  if (curChange == 1) {
    top.main.dMessages.style.display = 'inline';
  }
  ShowMessages(curChange);
  curChange=0;
}

function safit(txt) {
  if (txt == null) { return ''; }
  var sa = txt.toString()
  var re;
  re = /\</g; sa = sa.replace(re, "\&lt");
  re = /\>/g; sa = sa.replace(re, "\&gt");
  return sa;
}
var Shown = {};
function ShowMessages(wipe) {
  if (wipe==1) {
    var cnt = 0; for (var i in top.Mail) { cnt++; if (cnt > 1) { Shown[top.Mail[i]['MessageID']]=0; } }
  } else {
    var cnt = 0; for (var i in top.Mail) { cnt++; if (cnt > 1) { if (!Shown[top.Mail[i]['MessageID']]) { Shown[top.Mail[i]['MessageID']]=0; } } }
  }
  var cnt = 0;
  var tmp = "";
  for (var i in top.Mail) {
    cnt++;
    if (cnt > 1) {
      if (Shown[top.Mail[i]['MessageID']]==0) {
        var dt = top.Mail[i]['MsgDate'].split(" ");
        var thetime = dt[4]; if (!thetime) { thetime = dt[3]; }
        var thedate = dt[0]+" "+dt[1]+" "+dt[2];
        tmp += "<div id=MsgMarker"+i+" class='s_msg_rcvd'><table cellpadding=0 cellspacing=0 style='width:412;'><tr><td width=94 valign=top><a href=# class=s_msg_link_d style='margin-right:1px;' onclick='top.menu.MarkMessage("+top.Mail[i]['MessageID']+");MsgMarker"+i+".outerHTML=\"\";'>Del</a>&nbsp;<span style='margin-left:2px;margin-right:3px;'>Rcvd</span><span title='"+thedate+"'>"+thetime+"</span></td><td rowspan=2 valign=top style='padding-left:3px;'><span id=MessageTxt from='"+top.main.MsgSrc.innerText+"'>"+safit(top.Mail[i]['MsgTxt'])+"</span></td></tr></table></div>";
        Shown[top.Mail[i]['MessageID']] = 1;
      }
    }
  }
  if (wipe==1) { top.main.MsgTxt.innerHTML = tmp; } else { top.main.MsgTxt.innerHTML += tmp; top.main.MsgTxt.scrollTop = top.main.MsgTxt.scrollHeight-top.main.MsgTxt.offsetHeight+2; }
}
function MarkMessage(MessageID) {
  WebSubmit(top.UType,"MarkMessage","<input name='MessageID' value='"+MessageID+"'>","menu","MarkedMessage",'s','ClientServer');
}
function MarkedMessage(MessageID) {
  SubmitResult(1);SetWait(0);
}

function LockOut(cid) {
  top.WebSubmit(top.UType,"LockOutUser","<input name='UserID' value='"+cid+"'>","menu","LockedOut",'s','ClientServer');
}
function LockedOut(ret,named) {
  top.SubmitResult(1);top.SetWait(0);
  if (ret) {
    alert("Account Locked:"+named+"\nThis account has been locked out and the user has been shown a standard lockout message and an note was added.");
  } else {
    alert("Account Lockout Failed\nThere was a problem attempting to lockout this user, please try again.");
  }
}
function makeEmpty(id){
  id.value="";
}

function enterKey(){
  if (event.keyCode == 13) {
    stayOpen = 1;
    if (event.srcElement.name == 'nav_qorder') {
      stayOpen = 0;
      OrderNav(rlogin.nav_qorder.value);
    }
    if (event.srcElement.name == 'UPass') {
      dologin();
    }
    event.cancelBubble=true;
    event.returnValue=false;
  } else {
    event.cancelBubble=true;
    event.returnValue=true;
  }
}
function ChangeStatus(status){
  WebSubmit(top.UType,"ChangeChatStatus","<input name=Status value="+status+">","menu","ChangedStatus",'s','ClientServer');
}
function ChangedStatus(){
  SubmitResult(1);
  SetWait(0);
}
function HideSysMessage() {
  top.menu.dSysMessage.style.display = 'none';
  if (top.banner.dSysMessage) { top.banner.dSysMessage.style.display = 'none'; }
  top.main.dSysMessage.style.display = 'none';
}
function SysMessageRun(code) {
  try {
    eval(code);
    top.menu.HideSysMessage();
  } catch (e) {
    window.status = "Error running System Command! Please Notify Administrator";
  }
}
//top.menu.ShowSysMessage('Cache_Problem','Please_Clear_Your_Cache_to_Continue','top.menu.LogOff(top.UType)');
function ShowSysMessage(title,msg,arun,allowLogin,noclose) {
  if (!arun) { arun = ""; }  
  if (!top.menu.dSysMessage) { tmp = "<div id=dSysMessage class='opaque_bg'></div>"; top.menu.document.body.insertAdjacentHTML("beforeEnd",tmp); } if(typeof allowLogin == 'undefined' || allowLogin <= 0){top.menu.dSysMessage.style.display = 'inline'; }else{top.menu.dSysMessage.style.display = 'none';}  
  if (!top.banner.dSysMessage) { tmp = "<div id=dSysMessage class='opaque_bg'></div>"; top.banner.document.body.insertAdjacentHTML("beforeEnd",tmp); } if(typeof allowLogin == 'undefined' || allowLogin <= 0){top.banner.dSysMessage.style.display = 'inline'; }else{top.banner.dSysMessage.style.display = 'none';}
  if (!top.main.dSysMessage) {
    var cls = "";  if(noclose){ cls = "display:none;" }
    tmp = "<div id=dSysMessage style='display:inline;'><div class='opaque_bg' style='z-index:999999999;'></div><div class='s_dmsg_dialog' style='display:inline;z-index:999999999;position:absolute;height:280;width:430;top:expression(document.body.offsetHeight/2-140);left:expression(document.body.offsetWidth/2-215);'><div class='s_dmsg_title' id=dSysMessageHdr>"+title+" -- "+TimeStamp()+"</div><div class='s_dmsg_box' style='padding-bottom:10px;margin:2px;margin-top:0;padding:2px;overflow-y:show;'><table cellpadding=0 cellspacing=0 width=100% height=100%><tr><td align=center valign=middle><table cellpadding=0 cellspacing=0><tr><td class='s_dmsg_txt' id=dSysMessageTxt TABINDEX=1>"+msg+"</td></tr></table></td></tr></table></div><a id=dSysMessageRun Code='"+arun+"' TABINDEX=2 class=s_button href=# style='position:absolute;top:2;left:409;"+cls+"' onclick='top.menu.SysMessageRun(this.Code);'>X</a></div></div>";  
    top.main.document.body.insertAdjacentHTML("beforeEnd",tmp);
  } else {
    top.main.dSysMessageHdr.innerHTML = "<b style='padding-left:2px;font-size:12px;'>"+title+" -- "+TimeStamp()+"</b>";
    top.main.dSysMessageTxt.innerHTML = "<b style='font-size:12px;padding-left:4px;'>"+msg+"</b>";
    top.main.dSysMessageRun.Code = arun;
    top.main.dSysMessage.style.display = 'inline';
  }  
  return false;
}
function TimeStamp(){
  Stamp = new Date();
  var stampString = "";
  stampString += (Stamp.getMonth() + 1) +"/"+Stamp.getDate()+ "/"+Stamp.getYear() + '  ';
  var Hours;
  var Mins;
  var Time;
  Hours = Stamp.getHours();
  if (Hours >= 12) {
  Time = " P.M.";
  }
  else {
  Time = " A.M.";
  }
  if (Hours > 12) {
  Hours -= 12;
  }
  if (Hours == 0) {
  Hours = 12;
  }
  Mins = Stamp.getMinutes();
  if (Mins < 10) {
  Mins = "0" + Mins;
  }	
  stampString += Hours + ":" + Mins + Time;
  return stampString;
}
function HideMBXSplash() {
  top.main.dMBXSplash.style.display = 'none';
}
function ShowMBXSplash() {
  if (!top.main.dMBXSplash) {
    tmp = "<div id=dMBXSplash style='position:absolute;top:expression(document.body.offsetHeight/2-140);left:expression(document.body.offsetWidth/2-210);width:420;height:280;border:2px ridge #4040AA;cursor:hand;color:#000000;font-weight:bolder;font-size:11px;background-color:#FFFFFF;' onclick='top.menu.HideMBXSplash();'><center><br><br><a target=_new href=http://www.mindbrix.com><img src=/images/MindBrixLogo.gif border=0></a><br><a style='COLOR:#000099;FONT-WEIGHT:bold;FONT-FAMILY:tahoma;FONT-SIZE:20px;FONT-WEIGHT:bolder;TEXT-DECORATION:NONE;' target=_new href=http://www.mindbrix.com>www.mindbrix.com</a><br><br>Property Valuations Platform<br>Revision: "+top.VendorInfo.LastChangedRevision+"<br>Repository: "+top.VendorInfo.HeadURL+"<br>Date: "+top.VendorInfo.LastChangedDate+"<br><br>Copyright © 2002 MindBrix, L.P. All rights reserved.</center></div>";
    top.main.document.body.insertAdjacentHTML("beforeEnd",tmp);
  } else {
    top.main.dMBXSplash.style.display = 'inline';
  }
  return false;
}
var blinkInterval;

function NumMessages(newval) {
  if (!top.banner.dNewMessages) {
    tmp = "<div id=dNewMessages class=NewMessageBlinker style='visibility:visible;display:inline;cursor:hand;' onclick='top.menu.ShowNewMessages();'>You have "+newval+" Message(s)</div>";
    top.banner.document.body.insertAdjacentHTML("beforeEnd",tmp);
    top.banner.dNewMessages.style.display = 'inline';
    window.clearInterval(blinkInterval);
    blinkInterval = window.setInterval("DelayIt()", 500);
  }
  if (newval > parseInt(nummsg.innerText)) {
    top.banner.dNewMessages.innerHTML = "You have "+newval+" Message(s)";
    top.banner.dNewMessages.style.display = 'inline';
    top.banner.dNewMessages.style.visibility = 'visible';
    window.clearInterval(blinkInterval);
    blinkInterval = window.setInterval("DelayIt()", 500);
  } else if (newval <= parseInt(nummsg.innerText) && newval != 0){
    top.banner.dNewMessages.innerHTML = "You have "+newval+" Message(s)";
    top.banner.dNewMessages.style.display = 'inline';
    top.banner.dNewMessages.style.visibility = 'visible';
    window.clearInterval(blinkInterval);
  }
  nummsg.innerText = newval;
if (newval == 0) {
    window.setTimeout("top.banner.dNewMessages.style.display = 'none'",2000);
    window.clearInterval(blinkInterval);
  }
}
function DelayIt(){
  top.banner.dNewMessages.style.visibility = (top.banner.dNewMessages.style.visibility == 'visible') ? 'hidden' : 'visible';
}

function ShowNewMessages(){ //This is to display messages after clicking "You have _ Messages" 
  window.clearInterval(blinkInterval);
  var lObj = top.Users;
  var msgs = '';
  var re = /\'/g;
  
  for (var i in lObj){
    if (lObj[i]['Messages'] > 0){
      var stat = ""; var status="";
      if (lObj[i]['Status'] == 'P') { stat = "color:#"+top.tStyle.colors.d_menu_chat_P+";"; }
      if (lObj[i]['Status'] == 'F') { stat = "color:#"+top.tStyle.colors.d_menu_chat_F+";"; }
      if (lObj[i]['Status'] == 'O') { stat = "color:#"+top.tStyle.colors.d_menu_chat_O+";"; }//online -  blue
      if (lObj[i]['Status'] == 'B') { stat = "color:#"+top.tStyle.colors.d_menu_chat_B+";";status = "Busy: "; }//busy -  blue
      if (lObj[i]['Status'] == 'U') { stat = "color:#"+top.tStyle.colors.d_menu_chat_U+";"; }//signed off - lt grey
      if (lObj[i]['Status'] == 'I' && lObj[i]['Messages'] > 0) { stat = "color:#"+top.tStyle.colors.d_menu_chat_U+";"; }      
      if (lObj[i]['Status'] == ''  && lObj[i]['Messages'] > 0) { stat = "color:#"+top.tStyle.colors.d_menu_chat_U+";"; }//signed off - lt grey
      msgs += "<nobr><a class='chat' href=# onclick=\"top.menu.GetMessages("+lObj[i]['UserID']+",'"+lObj[i]['UserName'].replace(re, "\\\'")+"',1);\"><b style='padding:2px;color:#FF0000;font-size:13px;'>"+lObj[i]['Messages']+"</b>&nbsp;</a>";
      if(stat != "" && lObj[i]['Status'] != 'P'){
          msgs += "<a href='#' class='chat' oncontextmenu=\"return false;\" onclick=\"top.menu.GetMessages("+lObj[i]['UserID']+",'"+lObj[i]['UserName'].replace(re, "\\\'")+"',1);top.banner.dNewMessages.style.visibility = 'visible';\" style='"+stat+"font-size:13px'>"+"&nbsp;"+status+lObj[i]['UserName']+"</a></nobr><br>";
      }else if(stat != ""){
          msgs += "<a href='#' class='chat' oncontextmenu=\"return false;\" onclick=\"return false;\" style='"+stat+"font-size:13px'>"+"&nbsp;"+lObj[i]['UserName']+"</a></nobr><br>";
      }    
    }    
  }
  msgs += "<a onclick='top.main.dShowNewMessages.style.visibility=\"hidden\"' style='cursor:hand'>(X) Close</a>";  
  if(!top.main.dShowNewMessages){
    tmp = "<div id=dShowNewMessages class=ShowNewMessagesBox style='position:absolute;top:0;left:expression(document.body.offsetWidth-190);color:#000000;font-weight:bolder;font-size:13px;border: 1px solid #000000;background-color:white;width:100%;z-index:99999999;padding:1px;border-top:none;'>"+msgs+"</div>";
    top.main.document.body.insertAdjacentHTML("beforeEnd",tmp);
  } else if (msgs != '') {
    top.main.dShowNewMessages.innerHTML = msgs;
    top.main.dShowNewMessages.style.visibility='visible';
  }  
}

function OpenDialog(whtml,tag1,MBXserv) {
  tags = ""; if (tag1) { tags = "?"+tag1; }
  var wasCalled = false;
  try {
    top.main.ChangeDialog(whtml,tags);
    wasCalled = true;
  } catch (e) { }
  if (!wasCalled) {
    try {
      var dapp = ""; if (MBXClientServer) { dapp = parent.MBXServer[parent.CurrentApp].addr; if (MBXserv) { dapp = MBXserv; } }
      top.main.document.location.replace(dapp+"/"+top.utype+"/dialog/"+whtml+".html"+tags);
      wInit = 0;
    } catch (e) {
      window.status = "Re-Initializing Workspace";
      top.document.frames['main'].navigate("/cmd.html");
      window.setTimeout("OpenDialog('"+whtml+"','"+tag1+"')",500);
    }
  }
  if (event) { event.returnValue = false; }
}
function OrderNav(oid) {
  if(event){ //if the user pressed the enter key after entering a BPO# to search for
     if( event.keyCode == 13){
        event.cancelBubble=true;
        event.returnValue=false;
     }
  }
    var whtml;
    tags = ""; if (oid) { tags = "?search="+oid; }
    if(top.UType == 'V' && top.SysSettings.ServerID==2){
      tags = "?QueOrderType=B&OrderID="+oid;
      whtml = "PVAL_OrdSearch";
    }else if(top.UType == 'V'){
      tags = "?QuickSearch="+oid;
      whtml = "order_search";
    }else if(top.UType == 'C'){
      tags = "?QuickSearch="+oid;
      whtml = "order_search";
    }else if(top.UType == 'B'){
      whtml = "broker_orders";
    }else if(top.UType == 'A'){
      whtml = "profile";
    }
    try {
      var dapp = ""; if (MBXClientServer) { dapp = parent.MBXServer[parent.CurrentApp].addr; }  
      top.main.document.location.replace(dapp+"/"+top.utype+"/dialog/"+whtml+".html"+tags);
      if (top.UType == 'V' || top.UType == 'A') { top.menuframe.cols='4,*'; }
      wInit = 0;
    } catch (e) {
      ALERT("Error");
      window.status = "Re-Initializing Workspace";
      top.document.frames['main'].navigate("/cmd.html");
      window.setTimeout("OpenDialog('"+whtml+"','"+tag1+"')",500);
    }
}
function do_logout() { var oldUtype = top.UType; top.LoginID = ''; top.ContactID = ''; top.Password = ''; top.usertype = ''; top.UType = ''; LogOff(oldUtype); }
function CreateMenu(pre) {
  shtml = "<table cellspacing=0 cellpadding=0 class=\"mmenu_tbl\" id=tmenu>";
  menus = parent.menus;
  var hmapp = ""; var cnt = 0; for (var app in menus) { cnt++; }
  estyles = "style='vertical-align:bottom;'";
  for (var app in menus) {
    parent.CurrentApp = app;
    if (MBXClientServer) { if (app != 'hidden') { shtml += "<tr><td><table cellspacing=0 cellpadding=0><tr class=\"mmenu_app\" hideFocus><td><a class=mmenu_app href=\"#\" hideFocus onclick=\"ToggleApp('"+app+"');\" title=\""+parent.MBXServer[app].title+"\">"+parent.MBXServer[app].desc+"</a><br></td></tr>"; } }
    for (var i in menus[app]) {
      var ok = 0;
      var f = 1; var c = 0;
      if (MBXClientServer) { ok = 1; if (app != 'hidden') { hmapp = "display:none;"; } else { hmapp = ""; } } else { if (app == parent.DefaultApp) { ok = 1; } } if (app == 'hidden') { ok = 1; }
      if (ok == 1) {
        shtml += "<tr class=\"mmenu_row\" id='AppServer"+app+"' style='"+hmapp+"'><td class=\"mmenu_row\"><a class=mmenu mid='"+i+"' hideFocus href=\"#\" onclick=\"Toggle('"+i+"');\" title=\""+menus[app][i].title+"\">"+menus[app][i].desc+"</a><br></td></tr>";
        shtml += "<tr id='AppServer"+app+"'><td "+estyles+" >";
        for (var n in menus[app][i]) {
          if (n != 'title' && n != 'desc' && n != 'code') {
            if (f) { f = 0; }
            c++;
            shtml += "<div id='d"+i+"' style='display:none;'><a class=\"mmenu\" hideFocus style='vertical-align:bottom;' ";
            if (pre) { shtml += "target=main href=\""+menus[app][i][n].code+"\""; } else { shtml += "href=\"Javascript:"+menus[app][i][n].code+"\""; }
            shtml += " title='";
            shtml += menus[app][i][n].title;
            shtml += "'>";
            shtml += menus[app][i][n].desc;
            shtml += "<\/a><\/br><\/div>";
          }
        }
        if(c == 1) {//if only one submenu item, add a blank one at the end
          if(f) f=0;
          shtml += "<div id='d"+i+"' style='display:none;'><a class=\"mmenu\" hideFocus style='vertical-align:bottom;' ";
          if (pre) { shtml += "target=main href=\"\""; } else { shtml += "href=\"Javascript:\""; }
          shtml += " title=''><\/a><\/br><\/div>";
        }
        if (f) { shtml += "<div id='d"+i+"' style='display:none;'>"; }
        shtml += "</td></tr>";
      }
    }
    if (MBXClientServer) { if (app != 'hidden') { shtml += "</table></td></tr>"; } }
  }
  if (pre) {
    if(top.ShowWhatsNew == 1){
      shtml += "<TR class=\"mmenu_row\"><TD class=\"mmenu_row\"><A class=mmenu hideFocus target=main href='market/industry.html' onclick='' title='New offerings, industry current events and news'>Whats New?</A><br></TD></TR></table>";
    }
  } else {
    var dapp = ""; var mapp = ""; if (MBXClientServer) { mapp = "_app"; dapp = ",\"sys\"";}
    // CYNDI NO LONGER WANTS THIS if (top.SysSettings.ServerID==2 && top.UType == 'B') { shtml += "<TR class=\"mmenu_row\"><TD class=\"mmenu_row\"><A class=mmenu"+mapp+" hideFocus href='#' onclick='OpenDialog(\"profile\",\"upload=W9\""+dapp+");' title='Click Here to Upload your W9'>Upload W9</A><br></TD></TR>";  }
    if (typeof top.SysSettings != 'undefined' && top.SysSettings.ServerID==2 && (top.UType == 'B' || top.UType == 'V')) { 
      shtml += "<TR class=\"mmenu_row\"><TD class=\"mmenu_row\"><A class=mmenu"+mapp+" hideFocus href='#' onclick='OpenDialog(\"broker_pay\");' title='Click Here to view pay schedule'>Pay Schedule</A><br></TD></TR>";  
      shtml += "<TR class=\"mmenu_row\"><TD class=\"mmenu_row\"><A class=mmenu"+mapp+" hideFocus href='#' onclick=window.open('http://www.irs.gov/pub/irs-pdf/fw9.pdf?portlet=3') title='Click Here to IRS Website to download W9'>Download W9</A><br></TD></TR>";  
    }
    if (top.UType == 'C' && !top.Groups.match(/o/)) { } else { shtml += "<TR class=\"mmenu_row\"><TD class=\"mmenu_row\"><A class=mmenu"+mapp+" hideFocus href='#' onclick='OpenDialog(\"profile\",\"\""+dapp+");' title='Click Here to Manage Your User Account'>Edit My Profile</A><br></TD></TR></table>";  }
    if (postlogin.style.display == 'none') {
      var qs = 0;
      switch (top.UType){
        case 'C':QSlbl.innerHTML = 'Loan #';qs = 1;break;
        case 'V':QSlbl.innerHTML = 'Search';qs = 1;break;
        case 'A':break;
        case 'B':QSlbl.innerHTML = 'Order:';qs = 1;break;
        default:break;
      }
      if(qs){ prelogin.style.display = 'none'; postlogin.style.display = 'inline'; }
      sname.innerHTML = top.OptObj.User.FName + " " + top.OptObj.User.LName;
    }
    if (top.UType == 'B') { window.setTimeout("top.menu.document.all['tmenu'].children[0].children[0].children[0].children[0].fireEvent('onclick');",500); }
  }
  themenu.innerHTML = shtml;
  if (MBXClientServer) {
    if (cnt == 1) {
      if (parent.CurrentApp != 'hidden') {
        window.setTimeout("ToggleApp(parent.CurrentApp);",100);
      }
    } else {
      window.setTimeout("ToggleApp(parent.DefaultApp);",100);
    }
  }
}
function HideAllMenus(){
   themenu.innerHTML = '';
   prelogin.style.display = 'none';
   nohide.style.display = 'none';
   top.SetNavTab("<b>"+top.OptObj.User.FName + " " + top.OptObj.User.LName+"</b>");
}
//top.banner.Pop.document.all.MiniTxt.innerText = top.menu.themenu.innerHTML;

function urlDecode(str){
    str=str.replace(new RegExp('\+','g'),' ');
    return unescape(str);
}
function urlEncode(str){
    str=escape(str);
    str=str.replace(new RegExp('\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}

var END_OF_INPUT = -1;

var base64Chars = new Array(
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/'
);

var reverseBase64Chars = new Array();
for (var i=0; i < base64Chars.length; i++){
    reverseBase64Chars[base64Chars[i]] = i;
}

var base64Str;
var base64Count;
function setBase64Str(str){
    base64Str = str;
    base64Count = 0;
}
function readBase64(){
    if (!base64Str) return END_OF_INPUT;
    if (base64Count >= base64Str.length) return END_OF_INPUT;
    var c = base64Str.charCodeAt(base64Count) & 0xff;
    base64Count++;
    return c;
}
function encodeBase64(str){
    setBase64Str(str);
    var result = '';
    var inBuffer = new Array(3);
    var lineCount = 0;
    var done = false;
    while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT){
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[ inBuffer[0] >> 2 ]);
        if (inBuffer[1] != END_OF_INPUT){
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30) | (inBuffer[1] >> 4) ]);
            if (inBuffer[2] != END_OF_INPUT){
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6) ]);
                result += (base64Chars [inBuffer[2] & 0x3F]);
            } else {
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c)]);
                result += ('=');
                done = true;
            }
        } else {
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30)]);
            result += ('=');
            result += ('=');
            done = true;
        }
        lineCount += 4;
        if (lineCount >= 76){
            result += ('\n');
            lineCount = 0;
        }
    }
    return result;
}
function readReverseBase64(){
    if (!base64Str) return END_OF_INPUT;
    while (true){
        if (base64Count >= base64Str.length) return END_OF_INPUT;
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter]){
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') return 0;
    }
}

function ntos(n){
    n=n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}

function decodeBase64(str){
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
        && (inBuffer[1] = readReverseBase64()) != END_OF_INPUT){
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff)| inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT){
            result +=  ntos((((inBuffer[1] << 4) & 0xff)| inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT){
                result +=  ntos((((inBuffer[2] << 6)  & 0xff) | inBuffer[3]));
            } else {
                done = true;
            }
        } else {
            done = true;
        }
    }
    return result;
}

