/*
 * Copyright 1999 Netscape Communications Corp, a subsidiary of America Online
 */


var SieveStartPage
var searched = 0 // these three are fixes for searching
var s_search
var s_hold
var check_mail = 0 // a flag for the user checking mail
var view_message = 0 // a flag for the user viewing which message
                     // used in selectMsg()
/***********/
// set this to appropriate text and/or image to brand the top frame
// MUST specify height and width for Navigator 3.x to work
var brandht = 16
var brandwd = 1
var brandimg = 'imx/spacer.gif'

// bread crumb related variables
var breadCrumbList = new Array()
var lastBreadCrumb = 0
var lastBreadCrumbActive = false
var lastFolderisSpecial = true
var NNtoolRefresh = true
var displayedQuotaWarning = false
var displayedMsgQuotaWarning = false
var now = new Date()
var loaded = false
var state = 'init'		// init, mbox, msg, compose, folders
var sortid = new Array()
var sortBy = 'recv'		// from, recv, seen, size, subject, uid
var sortOrder = 'F'
var orgSort = ''
var compose_type		// new, reply, replyall, forward
var shutdown = ''
var oldMbox = ''
var sortno = 0
var srch = ''
var unique = now.getTime() & 0xFFF
var cmdOp = '', cfgOp = ''
var d_from = 0, d_to
var sd_from = 0, sd_to
var folderRefresh = false
var helpWindow, collectWindow, composeWindow, receiptWindow, pabEntryWindow, 
    pabGroupWindow, lookupWindow , folderPermissionWindow, SubscribeWindow , srchWin
var draftHdl
var option_page = 'summary'
var attr_list = new Array()
var searchForBody = 'false' // for 513276
var visitedMboxCB = 'false' // for 513276
var searchMessage = i18n['searching']
var mbox_from_msg=0
var start_id
var delete_selected=0
var deletelength
var folderpermisson
var folderacl
var isfolderprivate
var rtfPossible = 0
var meInitialized = ''
var vacCachesubject = ''
var vacCacheinternal = ''
var vacCachetext = ''
var vacCacheDirty = 0
var vacCachevalid = false
var vacCachestart
var vacCacheend
var vacCachechecked
var vacCachetimeout
var viewRTF;
var crumbUpdateNeeded = false; // Flag used to check if we need to refresh breadCrumb upon folder deletion.

helpoff = new Image();
helpoff.src = "imx/white_dot.gif";
userlogoutoff = new Image();
userlogoutoff.src = "imx/white_dot.gif";
helpover = new Image();
helpover.src = "imx/white.gif";
userlogoutover = new Image();
userlogoutover.src = "imx/white_dot.gif";

var formElement

/* Personal Address Book
 *        pabAttrs ... the server attribute name and flags object array
 *          curPab ... the current PAB un (universal name)
 *       lastModUn ... the last un modified (used for place saving in pages)
 *       curPabGrp ... the un of the current group
 *           ENTRY ... type constant used by PabSortObj
 *           GROUP ... type constant used by PabSortObj
 *         BY_NAME ... sort by name (default)
 *         BY_TYPE ... sort by type {entry, group}
 *         BY_MAIL ... sort by email address
 *       pabSrtIdx ... An array of sorted indexes into entry and group arrays
 *        pabSrtBy ... The current key for sorting
 *       pabSrtAsc ... Boolean - sort order is ascending if true (default)
 *     pabPageHead ... the beginning virtual index for a page
 *     pabPageTail ... the ending virtual index for a page (pabPageHead + cfg.meViewSize)
 */
var pabAttrs, curPab, curPabGrp = 1, ENTRY = 1, GROUP = 2, BY_NAME = 1, BY_TYPE = 2, BY_MAIL = 3;
var pabSrtIdx, pabSrtBy = BY_NAME, pabSrtAsc = true, pabPageHead = 0, pabPageTail = 0;

var argv, timer
var a, i, j, s

var accent0, accent1, accent2, bgcolor
var chrome0, chrome1, chrome2, chrome3
var link0, link1, link2
var positive, negative
var ch3_img
var black, white
var base_line
var cellBgString
var tableStart, tableEnd
var toolht, topht, fontht
var brand = '<img src="' + brandimg + '" vspace=2 width=' + brandwd +
  ' height=' + brandht + '>'

var font_delta = 0
var font_base = 2
var font_sizes = new Array('','xx-small','x-small','small','medium','large','x-large','xx-large')

var cfg = new Array()
var ui = new Array()
var people = new Array();
var groups = new Array();
var attr_list = new Array();

ui[0] = new Array('666699','9999CC','CCCCFF','666666','999999','CCCCCC','E6E6E6','gray90.gif','3333CC','3333CC','333366','FFFFFF','000000','FFFFFF','000000')
ui[1] = new Array('666699','660000','FFFFFF','666666','999999','CCCCCC','E6E6E6','gray90.gif','660000','660000','990000','FFFFFF','000000','FFFFFF','000000')
ui[2] = new Array('666699','000066','CCCCFF','336699','6699CC','99CCFF','E6E6E6','gray90.gif','000066','000066','000099','FFFFFF','000000','FFFFFF','000000')
ui[3] = new Array('666699','006666','CCFFFF','336666','669999','99CCCC','E6E6E6','gray90.gif','006666','006666','009999','FFFFFF','000000','FFFFFF','000000')
ui[4] = new Array('666699','006600','CCFFCC','336633','669966','99CC99','E6E6E6','gray90.gif','006600','006600','009900','FFFFFF','000000','FFFFFF','000000')
ui[5] = new Array('666699','666600','FFFFCC','666633','999966','CCCC99','E6E6E6','gray90.gif','666600','666600','999900','FFFFFF','000000','FFFFFF','000000')

a = split(window.location.search.substring(1, window.location.search.length), '&')
argv = new Array(a.length)
for (i = 0; i < argv.length; i++) {
  j = a[i].indexOf('=')
  if (j == -1)
    argv[a[i]] = true
  else
    argv[a[i].substring(0, j)] = a[i].substring(j + 1, a[i].length)
}

var initialMbox = argv['mbox']
var initialMsg = argv['msg']
var srcHREF = window.location.href.substring(0,
  window.location.href.lastIndexOf('?') - 1)
srcHREF = srcHREF.substring(0, srcHREF.lastIndexOf('/') - 1)
srcHREF = srcHREF.substring(0, srcHREF.lastIndexOf('/') + 1)

var msgHREF = argv['host']
var iconHREF = ''  // give the full path.

if (!msgHREF) {
    msgHREF = srcHREF
    rtfPossible = 1
}

var lang = argv['lang']
var sid = argv['sid']

function get_charset() {
  return (IE >= 4 ? '&charset=escaped_unicode' : '')
}

function clientargs() {
  return '&rtfPossible=' + (rtfPossible ? 'true' : 'false') + 
         '&security=' + security + '&lang=' + lang + get_charset()
}
      
var defaults = new Array(
  //'mailAutoReplyStartTime', '',
  //'mailAutoReplyStopTime', '',
  'vacationStartDate', '',
  'vacationEndDate', '',
  'mailAutoReplyTimeout', '0',
  'mailAutoReplySubject', '$SUBJECT',
  'mailAutoReplyTextInternal', i18n['vacation msg'],
  'mailAutoReplyText', i18n['vacation msg'],
  'mailQuota', '0',
  'preferredLanguage', lang,
  'meReplyToAddress', '',
  'meSignature', '',
  'meWrapIncoming', 'true',
  'meWrapWidth', '72',
  'meAutoQuote', 'true',
  'meToolText', 'true',
  'meToolImage', 'true',
  'meDraftFolder', '',
  'meSentFolder', '',
  'meTrashFolder', '',
  'mePageSize', '3000',
  'meViewSize', '20',
  'meFontSizeDelta', '0',
  'meTableSpacing', '2',
  'meFontFace', i18n['fontface'],
  'meColorSet', '0',
  'meSortOrder', 'F',
  'meSignature', '',
  'mePopAccount', '')

  var lastMessage = new Array();
  lastMessage['current_folder']=''

function lastMessageFolder(state,mboxstart,sortno,sort,sortorder){
  this.state=state
  this.mboxstart=mboxstart
  this.sortno=sortno
  this.sortBy=sort
  this.sortOrder=sortorder
}

function change() {
  refreshing = false
  if (IE > 0) {
    return
  } else if (mac && NN >= 4.0 && NN < 4.5 && isRefreshing()) {
    window.location.reload()
    return
  } else if (NN >= 4.0 && NN < 5) {
    window.location.reload()
    return
  } else if (mailFrame.appVersion && state != 'init') {
    setColor()
  } else {
    load(mailFrame, srcHREF + 'mbox_fs.html')
  }
}

function refreshLang() {
  if (state != 'init' && state != 'load' && lang != cfg['preferredLanguage'])
    alert(i18n['personal lang changed'])
}

function setColor() {
  if (IE && IE < 4 && cfgFrame.color && cmdFrame.color && mboxFrame.color && pabFrame) {
    cfgFrame.color('CC0000')
    cmdFrame.color('CC0000')
    mboxFrame.color('CC0000')
    msgFrame.color('CC0000')
    pabFrame.color('CC0000')
  }
}

function refreshColorSet() {
  var i = (cfg['meColorSet'] ? parseInt(cfg['meColorSet']) : 0)

  accent0  = ui[i][0]
  accent1  = bgcolor = ui[i][1]
  accent2  = ui[i][2]
  chrome0  = ui[i][3]
  chrome1  = ui[i][4]
  chrome2  = ui[i][5]
  chrome3  = ui[i][6]
  ch3_img  = ui[i][7]
  link0    = ui[i][8]
  link1    = ui[i][9]
  link2    = ui[i][10]
  positive = ui[i][11]
  negative = ui[i][12]
  white    = ui[i][13]
  black    = ui[i][14]
  base_line = ' valign=' + (IE >= 3 && IE < 4 ? 'top' : 'baseline')
  font_delta = parseInt(cfg['meFontSizeDelta'])
  if ((NN >= 4 && screen.pixelDepth > 8) || 
    (IE >= 4 && screen.colorDepth > 8)) {
    cellBgString = 'bgcolor=' + chrome3
    tableStart = '<table border=0 cellpadding=' + cfg['meTableSpacing'] +
      ' cellspacing=1 width=100%>\n'
    tableEnd = '</table>\n'
  } else {
    if (NN >= 4)
      cellBgString = 'background="imx/' + ch3_img + '"'
    else
      cellBgString = 'bgcolor=' + positive
    tableStart = '<table border=0 cellpadding=0 cellspacing=0 width=100%>' +
      '<tr><td bgcolor=' + chrome2 + '>' +
      '<table border=0 cellpadding=' + cfg['meTableSpacing'] +
      ' cellspacing=1 width=100%>\n'
    tableEnd = '</table></td></tr></table>\n'
  }
  fontht = (mac ? 10 : 14) + font_delta * 2
  topht = (brandht < fontht ? fontht : brandht) + 15 + fontht + (NN >= 3 && NN < 5 ? 3 : 0)
  if (cfg['meToolImage'] == 'true')
    toolht = 35 + (cfg['meToolText'] == 'true' ? fontht + 4 - (font_delta < 0 ? 0 : 2) : (NN > 4  ? 14 : 0 )) + (IE >= 3 ? 6 : 8)
  else {
    toolht = fontht + (mac || NN < 4 || NN >= 5 ? 12 : 28)
    if(mac) toolht += 15
  }
  toolht += 35 // VIG: Added for now, exact value to be decided upon review
  if (/*NN >= 3 && NN < 4 &&*/ toolht < 32)
    toolht = 47
}

function font(size, color, face) {
  var s = ''

  if(size == null)
  size=font_base
  size += font_delta
  if (size < 1)
    size = 1
  if ((IE > 4 && NN > 5) || size != font_base + font_delta)
    s += ' size=' + size
  else if(NN >=4.0 && NN < 5)
    s += ' size=' + size
  if (!(IE < 4 && NN < 5 && (lang == 'zh-CN' || lang == 'zh-TW' || lang == 'ar' || lang == 'jp')))
    s += ' face="' + cfg['meFontFace'] + '"'

  if (color)
    s += ' color=' + color
  return s == '' ? s : '<font' + s + '>'
}

function get_form_charset() {
  return ""
}

function exec(op, mboxname /* arg1, arg2, ..., callback */) {
  var s = msgHREF + 'cmd.msc?sid=' + sid + '&mbox=' + encode(mboxname) + '&cmd=' + op

  for (i = 2; i < exec.arguments.length - 1; i++)
    s += '&argv=' + encode(exec.arguments[i])
  cmdOp = exec.arguments[i]
  load(cmdFrame, s)
}

function refreshCfg() {
  load(cfgFrame, msgHREF + 'cfg.msc?sid=' + sid)
}

function refreshFolders() {
  refreshCfg()
}

function refreshCurrMbox() {
  refreshMbox(mboxFrame.mbox)
}

function mboxEquals(mb1, mb2) { // test equality - adjusting for 'INBOX' vs 'Inbox'
  if(mb1 == 'INBOX') {
    mb1 = i18n['INBOX']
  }
  if(mb2 == 'INBOX') {
    mb2 = i18n['INBOX']
  }

  return mb1 == mb2;
}

function isDesignatedFolder(f) {
  return f==cfg['meSentFolder'] || f==cfg['meDraftFolder'] ||
         f==cfg['meTrashFolder'] ;
}

function refreshMbox(f, search, hold) {
  var s

  if (search == null) {
     search = srch = ''
  } else {
    srch = hold
    folderRefresh = true
  }

  if (orgSort != cfg['meSortOrder']) {
     sortOrder = cfg['meSortOrder']
     orgSort = sortOrder
  }

  if (f == null)
    f = i18n['INBOX']

  oldMbox = mboxFrame.mbox 

  if (check_mail == 1) {
    searched = 0
    check_mail = 0
    state = 'Inbox'
    constructBreadCrumb(fldr['INBOX'], true, true)
    if (mboxFrame.mbox != 'INBOX')
      d_from = 0
    load(mailFrame, srcHREF + 'mbox_fs.html')
  }
  else {
    var spFlag = true
    var fname = f

    if(f.toUpperCase()=='INBOX') {
    
      fname = fldr['INBOX']
    }
    else if(isDesignatedFolder(f)) {
      if(f==cfg['meSentFolder']) {
        if(f==i18n['sent folder']) {
          fname = fldr['Sent']
        }
        else {
          spFlag = false
        }
      }
      else if(f==cfg['meDraftsFolder']) {
        if(f==i18n['draft folder']) {
          fname = fldr['Drafts']      
        }
        else {
          spFlag = false;
        }
      }
      else if(f==cfg['meTrashFolder']) {
        if(f==i18n['trash folder']) {
          fname = fldr['Trash'];
        }
        else {
          spFlag = false
        }
      }
    }
    else {
      state = 'mbox';spFlag = false
    }

    constructBreadCrumb(fname,true,spFlag)
  }

if(mbox_from_msg==3)
 {
  mbox_from_msg=0;
  if(sortid.length==0)
    {
     d_from=mboxFrame.start-mboxFrame.count
     if(d_from < 0) d_from=0;
    }
  else {
  d_from=mboxFrame.start;
	}
 }
if(mbox_from_msg==2)
{
 d_from=mboxFrame.start+mboxFrame.count
} 

    var folder=f;
    folder=(f=='Inbox'|| f=='INBOX')?'INBOX' :folder;
    if(lastMessage['current_folder']=='' || folder!=lastMessage['current_folder'])
      {
      if(lastMessage[folder])
        {
      d_from=lastMessage[folder].mboxstart;
      sortBy=lastMessage[folder].sortBy;
      sortOrder=lastMessage[folder].sortOrder;
      if(lastMessage[folder].state=="msg")
      mbox_from_msg=13;
        }
      }

  s = msgHREF + 'mbox.msc?sid=' + sid + '&mbox=' +
    encode(f) + '&start=' + d_from + '&count=' + cfg['meViewSize'] + 
    '&date=true&sortorder=' + sortOrder + '&sortby=' + sortBy + 
    '&headerv=Content-type&srch=' + encode(search)

  if (state == 'Sent' || state == 'Drafts')
    s += '&hdr=to'

  load(mboxFrame, s)
}

function selectMbox(idx) {
  var mb
  if(idx < 0) return // possibly from a select menu, so do nothing
  d_from = 0
  searched = 0
  view_message = 0
  var spFlag = true

  if (idx < cfgFrame.mbox.length) {
    if(cfgFrame.mbox[idx].flags & cfgFrame.flag['\\noselect']){
      alert(i18n['fldr cannotselect']);
      return;
    }
    mb = main.cfgFrame.mbox[idx].name
    if(mb.toUpperCase() == 'INBOX') mb = 'INBOX'
  }
  else {
    if(cfgFrame.sub[idx - cfgFrame.mbox.length].flags & cfgFrame.flag['\\noselect']){
      alert(i18n['fldr cannotselect']);
      return;
    }

    mb = main.cfgFrame.sub[idx - main.cfgFrame.mbox.length].name
    if(mb.toUpperCase() == 'INBOX') mb = 'INBOX'
  }

  state = 'mbox'
 
  if(mb == 'INBOX')
    state = 'Inbox'
  else if(mb == cfg['meSentFolder'])
    state = 'Sent'
  else if(mb == cfg['meTrashFolder'])
    state = 'Trash'
  else if(mb == cfg['meDraftFolder'])
    state = 'Drafts'
  else
    spFlag = false

  constructBreadCrumb(mb,true,spFlag)
  refreshMbox(mb)
}

function selectUid(num, selectmbox) {
  if (num == null) {
    selectMsg(0)
    return
  }

  if (selectmbox == null) {
    selectmbox = mboxFrame.mbox
  }

  state = mapFolderToState(selectmbox)
  sortno = 0
  view_message =0
  d_from = 0

  binhex = mac ? '' : ',binhex'
  if (NN > 0 && NN < 5)
    maxtext = '&maxtext=30700'
  else if (IE >= 3 && IE < 4)
    maxtext = '&maxtext=23500'
  else
    maxtext = '&maxtext=55000'
  constructBreadCrumb('',false); // make the current folder a link
  load(msgFrame, msgHREF + 'msg.msc?sid=' + sid  +
    '&mbox=' + encode(selectmbox) + '&uid=' + num +
    '&process=js,link,target,html' + binhex + maxtext)
}

var currentlyFolder;
function selectMsg(num) {
/*  var lbl = breadCrumbList[lastBreadCrumb].label
  if( currentlyFolder && lbl != fldr['INBOX'] && !isSpecialFolderState(lbl))
*/
  constructBreadCrumb('',false); // make the current folder a link
  if (num != null)
    sortno = num
  if (view_message == 0 && num == null && sortno != 0)
    sortno = 0
  if (view_message != 0 && num == null) 
    sortno = view_message

  if (sortid.length == 0 || sortno < 0 || sortno >= sortid.length) {
    sortno = -1
    state = 'mbox'
    load(mailFrame, srcHREF + 'mbox_fs.html')
    return
  } 

    var page = parseInt(cfg['meViewSize'])
    var i = 0, j = 0
    var msg
    for (msg = 0; msg < sortid.length; msg++) {
      if (i++ == page) {
        i = 1
	j = msg;
      }
      if (msg == sortno) {
        d_from = j
        break;
      }
    }

    view_message = sortno

    if (((mboxFrame.mbox).toLowerCase()=='drafts')||(mboxFrame.msg[sortid[sortno]].flags & mboxFrame.flag['\\draft']) ){
      load(msgFrame, msgHREF + 'msg.msc?sid=' + sid + '&mbox=' + 
           encode(mboxFrame.mbox) + '&uid=' + mboxFrame.msg[sortid[sortno]].uid)
    } else if (msgFrame.mbox != null && msgFrame.mbox == mboxFrame.mbox &&
      msgFrame.uid == mboxFrame.msg[sortid[sortno]].uid) {
      if (msgFrame.errno != 0) {
        alert(msgFrame.errstr)
        return
      }
      state = 'msg'
      load(mailFrame, srcHREF + 'msg_fs.html')
    } else {
      var binhex, maxtext

      binhex = mac ? '' : ',binhex'
      if (NN > 0 && NN < 5)
	maxtext = '&maxtext=30700'
      else if (IE >= 3 && IE < 4)
	maxtext = '&maxtext=23500'
      else
	maxtext = '&maxtext=55000'
      load(msgFrame, msgHREF + 'msg.msc?sid=' + sid + 
        '&mbox=' + encode(mboxFrame.mbox) + '&uid=' + mboxFrame.msg[sortid[sortno]].uid +
        '&process=js,link,target,html' + binhex + maxtext)
    }
/*
  }
*/
}

function selectOptions() {
  state = 'options'
  constructBreadCrumb(null,false)
  load(mailFrame, srcHREF + 'opts_fs.html')
}

function restart() {
    var ref = window.document.referrer != '' ? window.document.referrer : '/'
    if (ref.indexOf('mail.html') > 0)
	ref = '/'
    var ind = ref.indexOf('?')
    self.location.replace(ind > 0 ? ref.substring(0, ind) : ref)
}

function exit() {
  if (shutdown == 'exit')
    return
  shutdown = 'exit'
  if (helpWindow)
    helpWindow.close()
  if (collectWindow)
    collectWindow.close()
  if (receiptWindow)
    receiptWindow.close()
  if (pabEntryWindow)
    pabEntryWindow.close()
  if(folderPermissionWindow)
    folderPermissionWindow.close()
  if(SubscribeWindow)
    SubscribeWindow.close()
  if(srchWin && !srchWin.closed)
    srchWin.close()
  if(lookupWindow)
    lookupWindow.close()
  window.setTimeout('restart()', 50)
}

function cleanup() {
  exec('logout', '', 'exit()')
}

function logout(unload) {
  shutdown = 'logout'
  if (cfg['meExpungeOnExit']) {
    if (cfg['meTrashFolder'])
      exec('expunge', cfg['meTrashFolder'], '1:*', 'force', 'cleanup()')
    else
      exec('expunge', 'INBOX', 'cleanup()')
  } else {
    cleanup()
  }
}

function folder(idx) {
  idx = parseInt(idx)
  if (idx < 0)
    return cfgFrame.namespace['personal']
  else if (idx < cfgFrame.mbox.length)
    return cfgFrame.mbox[idx].name
  else if (idx == cfgFrame.mbox.length + cfgFrame.sub.length)
    return cfgFrame.namespace['other']
  else
    return cfgFrame.sub[idx - cfgFrame.mbox.length].name
}

function getfolderacl(idx){
   idx = parseInt(idx);
   if(idx < cfgFrame.mbox.length)
    return cfgFrame.mbox[idx].acl
   else if(idx <= cfgFrame.mbox.length + cfgFrame.sub.length)
    return cfgFrame.sub[idx - cfgFrame.mbox.length].acl
}

function checkFolderPermission(i , permission)
{

var foldername = main.folder(i);
var folderacl = main.getfolderacl(i);
var foldertree = split(folderacl,'\t')
var createpermission = 0

for(var j =0; j < foldertree.length; j= j+2)
   {
        if(foldertree[j] == main.cfg['uid'])
           {
               for(var k =0; k < foldertree[j+1].length;k++)
                {
                      if(foldertree[j+1].charAt(k) == permission)
                       {
                             createpermission = 1
                             break;
                       }
                }
           }
        else if (foldertree[j] == 'anyone' )
          {
              for(var k =0; k < foldertree[j+1].length;k++)
                {
                      if(foldertree[j+1].charAt(k) == permission)
                       {
                             createpermission = 1
                             break;
                       }
                }
          }
       if(createpermission == 1)
        break;
   }
     return createpermission;
}

function getPublicUser()
{
  var publicuser = "public";

  if(cfgFrame.defaultdomain != cfgFrame.mailDomain)
     publicuser +=   '@' + cfgFrame.mailDomain;

  return publicuser;
}


function folderSelectionBreadCrumbs(name, func, hdr, root, skip, sel,share,op) {
  var mbl = cfgFrame.mbox
  var s
  var z = -7
  var nopermission = -8
  var noselfmove = -9
  var fldr_name

  s = '<select id="folderList" name="' + name + '"'
  if (func)
    s += ' onChange="' + func + '"'
  s += '>\n'
  if (hdr)
    s += '<option selected>' + hdr + '</option>\n'
    s += '<option value="-1">' + i18n['fldr personal'] + '</option>\n'
   s+='<option value="-2">'+'-------------' +'</option>\n'
   for (var i = 0; i < mbl.length; i++) {
    temp = split(mbl[i].name, '/')
    s += '<option '
    if (skip != null && mbl[i].name.toLowerCase() == skip.toLowerCase())
         s += 'value="' + noselfmove + '">'
    //temp = split(mbl[i].name, '/')
    //s += '<option '
    else if((mbl[i].flags & cfgFrame.flag['\\noselect']))
    {
        if(op == 'movefldr')
                s += 'value="' + i + '">'
        else
                s += 'value="' + z + '">'

    }else
    {
        var ind = i, actual_fld
        if (sel && mboxEquals(mbl[i].name,sel))
                s += 'selected '
        if(temp.length == 1 && fldr[temp[0]]) {
          if(temp[0] == 'INBOX')
            actual_fld = temp[0]
          else if(temp[0] == 'Trash')
            actual_fld = cfg['meTrashFolder']
          else if(temp[0] == 'Sent')
            actual_fld = cfg['meSentFolder']
          else if(temp[0] == 'Drafts')
            actual_fld = cfg['meDraftFolder']
          ind = getMboxIndex(actual_fld)
        }
        s += 'value="' + i + '">'
    }
    for (var j = 1; j < temp.length; j++)
      s += '. . '
    if (temp.length == 1){
       if(temp[0] == 'INBOX' || temp[0] == 'Trash' || temp[0] == 'Sent' || temp[0] == 'Drafts')
            s += fldr[temp[0]]
       else {
        s +=  html(temp[0])
       }
    }
    else {
        s += html(temp[temp.length - 1])
    }
    if ((mbl[i].flags & cfgFrame.flag['\\noselect']))
      s += i18n['noselect folder']
    s += '</option>\n'
  }
if(share && share.length!=0){
s+='<option value="-4">'+ i18n['fldr shared'] +'</option>\n'
s+='<option value="-3">'+'-------------' +'</option>\n'

var publicuser = main.getPublicUser();

for (var j = 2; j< share.length; j++) {
  var value = 'value="' + (i+j) + '">'
  temp = split(share[j].name, '/')
  if(op != null & op == 'move')
    {
        var write =  0
        write = checkFolderPermission( j + i, 'w')
        if( write == 0 )
           value = 'value="' + nopermission  + '">'
     }
   if(op != null & op == 'movefldr')
{
        var manage =  0
        manage = checkFolderPermission( j + i, 'a')
        if( manage == 0 )
           value = 'value="' + nopermission  + '">'
     }
    if (skip != null && share[j].name.toLowerCase() == skip.toLowerCase())
           value = 'value="' + noselfmove  + '">'
    if(temp[2] != publicuser)
        continue;
    if(temp.length==3)
        continue;
    s += '<option '
    if (sel && mboxEquals(share[j].name,sel))
      s += 'selected '
    s += value
    var l = temp.length - 4;
    for (var k = 0; k< l; k++)
      s += '. . '
     s += html(temp[temp.length - 1])
     if ((share[j].flags & cfgFrame.flag['\\noselect']))
         s += i18n['noselect folder']
     s += '</option>\n'
  }

for (var j = 2; j< share.length; j++) {
  var value = 'value="' + (i+j) + '">'
  temp = split(share[j].name, '/')
  if(op != null & op == 'move')
    {
        var write =  0
        write = checkFolderPermission( j + i, 'w')
        if( write == 0 )
           value = 'value="' + nopermission  + '">'
     }
   if(op != null & op == 'movefldr')
    {
        var manage =  0
        manage = checkFolderPermission( j + i, 'a')
        if( manage == 0 )
           value = 'value="' + nopermission  + '">'
}
    if (skip != null && share[j].name.toLowerCase() == skip.toLowerCase())
           value = 'value="' + noselfmove  + '">'

     if(temp[2] == publicuser)
         continue;

if(temp.length==3){
  s += '<option value='+(z-1) +'>' +temp[temp.length-1]+ '</option>\n'
  continue; }
s += '<option '
    if (sel && mboxEquals(share[j].name,sel))
      s += 'selected '
    s += value
//  if(temp.length==4)
//      s+='.  '
    //var l = (temp[2] != 'public') ? temp.length - 3 : temp.length - 4;
    var l = temp.length - 3;
    for (var k = 0; k< l; k++)
      s += '. . '
      s += html(temp[temp.length - 1])
if ((share[j].flags & cfgFrame.flag['\\noselect']))
      s += i18n['noselect folder']
    s += '</option>\n'
}
}
s += '</select>\n'
  return s
}

function folderSelection(name, func, hdr, root, skip, sel,share) {
  var mbl = cfgFrame.mbox
  var s
  var z = -7
  s = '<select id="folderList" name="' + name + '"'
  if (func)
    s += ' onChange="' + func + '"'
  s += '>\n'
  if (hdr)
    s += '<option selected>' + hdr + '</option>\n'
    s += '<option value="-1">' + i18n['fldr personal'] + '</option>\n'
   s+='<option value="-2">'+'-------------' +'</option>\n'
   for (var i = 0; i < mbl.length; i++) {
    if (skip != null && mbl[i].name.toLowerCase() == skip.toLowerCase())
      continue
    temp = split(mbl[i].name, '/')
    s += '<option '
    if (sel && mboxEquals(mbl[i].name,sel))
      s += 'selected '
    s += 'value="' + i + '">'
    for (var j = 1; j < temp.length; j++)
      s += '. . '
    if (temp.length == 1){
      if(temp[0] == 'INBOX' || temp[0] == 'Trash' || temp[0] == 'Sent' || temp[0] == 'Drafts')
            s += fldr[temp[0]]
       else {
        s +=  html(temp[0])
       }
    }
    else
      s += html(temp[temp.length - 1])
    if ((mbl[i].flags & cfgFrame.flag['\\noselect']))
      s += i18n['noselect folder']
    s += '</option>\n'
  }
if(share && share.length!=0){
s+='<option value="-4">'+ i18n['fldr shared'] +'</option>\n'
s+='<option value="-3">'+'-------------' +'</option>\n'
for (var j = 0; j< share.length; j++) {
    if (skip != null && share[j].name.toLowerCase() == skip.toLowerCase())
      continue
    temp = split(share[j].name, '/')
if(temp.length==3){
  s += '<option value='+(z-1) +'>' +temp[temp.length-1]+ '</option>\n'
  continue; }
s += '<option '
    if (sel && share[j].name == sel)
      s += 'selected '
    s += 'value="' + (i+j+2) + '">'
  if(temp.length==4)
      s+='.  '
    for (var k = 4; k< temp.length; k++)
      s += '. . '
      s += html(temp[temp.length - 1])
if ((share[j].flags & cfgFrame.flag['\\noselect']))
      s += i18n['noselect folder']
    s += '</option>\n'
} 
}
s += '</select>\n'
  return s
}
function displayFolders(refresh) {

var locationvar = mailFrame.location.pathname; // for bug 531566

constructBreadCrumb(null,false);

if(state!='folders')
{
state='folders';
refreshFolders();
}
else
{
if(folderRefresh)
  	{
	state='folders'
	refreshFolders();
  	}
else 	{
	if(refresh && locationvar.search("fldr_fs.html")!=-1)
		{
		mailFrame.refresh(); 
		}
	else
		{
		state='folders'
		load(mailFrame,srcHREF + 'fldr_fs.html')
		}
	}
}
}


function displayMbox(fast) {
  if (state == 'mbox' && mailFrame.displayMbox) {
    if (mailFrame.toolFrame)
      mailFrame.displayMbox(fast)
  } else {
    if(state == 'load' || state == 'init')
      state = 'Inbox'
    else if(!isSpecialFolderState(state))
      state = 'mbox'

    load(mailFrame, srcHREF + 'mbox_fs.html')
  }
}


function sortMsgs(by) {
  sortBy = by
  if (sortOrder == 'F')
    sortOrder = 'R'
  else 
    sortOrder = 'F' 
  refreshCurrMbox()
}

function mark(del /* ... */) {
  var i, j, k = 1

  for (i = 0; i < sortid.length && k < mark.arguments.length; i++) {
    for (j = 1; j < mark.arguments.length; j++) {
      if (mboxFrame.msg[sortid[i]].uid == mark.arguments[j]) {
        var msg = mboxFrame.msg[sortid[i]]
        if (del)
      	  msg.flags |= mboxFrame.flag['\\deleted']
      	else
      	  msg.flags &= ~mboxFrame.flag['\\deleted']
      	k++
        break
      }
    }
  }
}


function CallBack()
{
   folderPermissionWindow.close()
   folderPermissionWindow = null
   refreshCfg()
 
}


function move(dest, src /* uid, ... */) {
  var a = new Array()
  var i, j, k = 0, x = 0
  var l = cfgFrame.mbox
  var idx = -1, size = 0, count = 0

  if (move.arguments.length <= 2)
    return

  if( dest == -8)
  {
   	alert(i18n['mbox nopermission']);
        return;
  }

  if( dest == -9 )
  {
  	alert(i18n['mbox selfmove']);
        return;
  }
 
  if (!src)
    src = mboxFrame.mbox
  for (i = 0; i < sortid.length; i++) {
    for (j = 2; j < move.arguments.length; j++) {
      if (mboxFrame.msg[sortid[i]].uid == move.arguments[j])
        break
    }
    if (j == move.arguments.length) {
        a[k++] = sortid[i]
    } else {
      if (sortno == i)
        sortno = -1
      else if (sortno >= i)
        x++
      if (mboxFrame.msg[sortid[i]].flags & mboxFrame.flag['\\seen'])
        mboxFrame.seen--
      size += mboxFrame.msg[sortid[i]].size
      count++
    }
  }
  for (i = 0; i < l.length; i++) {
    if (l[i].name == dest) {
      l[i].msgs += count
      l[i].size += size
    } else if (l[i].name == src) {
      l[i].msgs -= count
      l[i].size -= size
      if (l[i].size < 0 || l[i].msgs == 0)
	l[i].size = l[i].msgs = 0
      idx = i
    }
  }
  if (idx == -1) {
    l = cfgFrame.sub
    for (i = 0; i < l.length; i++) {
      if (l[i].name == src) {
	l[i].msgs -= count
	l[i].size -= size
	if (l[i].size < 0 || l[i].msgs == 0)
	  l[i].size = l[i].msgs = 0
	break
      }
    }
  }
  if (dest == null)
    main.mboxFrame.mailQuotaUsed = (parseInt(main.mboxFrame.mailQuotaUsed) - size) + ''
  sortid = a
  if (d_from >= sortid.length)
    d_from = 0
  if (sortno != -1)
    sortno -= x
}
function copy() {
selectMsg();
}

function message(uid, size, recv, flags, from, subject) {
  this.uid = uid
  this.size = size
  this.recv = recv
  this.flags = flags
  this.from = from
  this.subject = subject
}

function add(fldr, uid, size, recv, flags, from, subject) {
  var i, l = cfgFrame.mbox

  for (i = 0; i < l.length; i++) {
    if (l[i].name == fldr) {
      l[i].size += size
      l[i].msgs++
      break
    }
  }
  if (mboxFrame.mbox == fldr && uid != 0) {
    sortid[sortid.length] = mboxFrame.msg.length
    mboxFrame.msg[mboxFrame.msg.length] = new message(uid, size, recv,
      flags, from, subject)
    if (state == 'mbox')
      displayMbox()
  }
  if (state == 'folders')
    displayFolders()
}

function isFldr(f) {
  for (var i = 0; i < cfgFrame.mbox.length; i++)
    if (cfgFrame.mbox[i].name == f)
      return true
  return false
}

function confirmMeInit() {
  setUserAttrValue('meInitialized', 'true')
  meInitialized = 'true'
  submitUserAttrChanges()
}

function initAccount() {
  var f, s = ''

  f = i18n['draft folder']
  setUserAttrValue('meDraftFolder', f)
  cfg['meDraftFolder'] = f
  if (!isFldr(f))
    s = '&mbox=' + encode(f)
  f = i18n['sent folder IE']
  if (!isFldr(f))
    f = i18n['sent folder']
  setUserAttrValue('meSentFolder', f)
  cfg['meSentFolder'] = f
  if (!isFldr(f)) {
    if (s == '')
      s = '&mbox=' + encode(f)
    else
      s += '&argv=' + encode(f)
  }
  f = i18n['trash folder']
  setUserAttrValue('meTrashFolder', f)
  cfg['meTrashFolder'] = f
  if (!isFldr(f)) {
    if (s == '')
      s = '&mbox=' + encode(f)
    else
      s += '&argv=' + encode(f)
  }
  if (s == '') {
    confirmMeInit()
  } else {
    cmdOp = 'confirmMeInit()'
  }
  return s
}

/* start of callback functions */
function cmdCB() {
  var s = cmdOp

  if (isRefreshing())
    return
  cmdOp = ''
  if (cmdFrame.errno != 0) {
    alert(cmdFrame.errstr)
    return
  }
  if (s.length == 0)
    noaction()	// prevent refresh

  if(IE>4 && mac && s =='exit()') {
    var ref = window.document.referrer != '' ? window.document.referrer : '/'
    var ind = ref.indexOf('?')
    window.top.location.href = ind > 0 ? ref.substring(0, ind) : ref
  }
  else 
    eval(s)
}

///////AK SMIME Nov 21///////
var applet_loaded=false;
var applet_mid=-1;
var applet_init=false;
var applet_destroy=false;
///////AK SMIME Nov 21///////

var submitted=false;
function cfgCB() {
  var a, i, found

  if (isRefreshing())
    return
  if (cfgFrame.errstr) {
    cfgOp = ''
    if (state == 'load') {
      alert(i18n['login failed'])
      exit()
    } else {
      main.vacCacheDirty &= 127
      alert(cfgFrame.errstr)
    }
    return
  }
  // set Webmail Preferences
  if (state == 'init' || state == 'load')
    cfg = new Array()

  if (state == 'init' || state == 'load') {
     if (cfgFrame.SievePort) {
       var s = srcHREF.substring(0, srcHREF.lastIndexOf('/'))
       var ps = s.lastIndexOf('/')
       var pc = s.lastIndexOf(':')
       ps = (pc > ps) ? pc : s.length
       SieveStartPage = s.substring(0, ps) +':'+cfgFrame.SievePort+'/MailFilter/main/Sieve'
     }
    for (i = 0; i < cfgFrame.usrattrval.length; i++) {
      if (cfgFrame.usrattrval[i].vals.length == 0) {
        cfg[cfgFrame.usrattrval[i].name] = ''
      } else if (cfgFrame.usrattrval[i].vals.length == 1) {
        if (cfgFrame.usrattrval[i].name == "mailAutoReplySubject" ||
            cfgFrame.usrattrval[i].name == "mailAutoReplyTextInternal" ||
            cfgFrame.usrattrval[i].name == "mailAutoReplyText")
          cfg[cfgFrame.usrattrval[i].name] = cfgFrame.usrattrval[i].vals[0]
        else
          cfg[cfgFrame.usrattrval[i].name] =
          unescape_crlf(cfgFrame.usrattrval[i].vals[0])
      } else {
        cfg[cfgFrame.usrattrval[i].name] = new Array()
        for (var j = 0; j < cfgFrame.usrattrval[i].vals.length; j++) {
          if (cfgFrame.usrattrval[i].name[j] == "mailAutoReplySubject" ||
              cfgFrame.usrattrval[i].name[j] == "mailAutoReplyTextInternal" ||
              cfgFrame.usrattrval[i].name[j] == "mailAutoReplyText")
            cfg[cfgFrame.usrattrval[i].name][j] = cfgFrame.usrattrval[i].vals[j]
          else
            cfg[cfgFrame.usrattrval[i].name][j] =
            unescape_crlf(cfgFrame.usrattrval[i].vals[j])
        }
      }
    }
  } else {
    var name, val, tmp;
    if (uavAddList) {
      for (i = 0; i < uavAddList.length; i++) {
        name = uavAddList[i].substring(0, uavAddList[i].indexOf('='))
        val = uavAddList[i].substring(uavAddList[i].indexOf('=') + 1)
        for(j=0;j<cfg[name].length;j++)
	{
	  if(val==cfg[name][j]) 
		{
		found=1
		break
		}
        found=0
	}
	if(found) continue
	if(!val) continue

        if (isArray(cfg[name]))
          cfg[name][cfg[name].length] = val
        else if (!cfg[name] && uavAddList.length == 1) 
          cfg[name] = val
        else {
          tmp = cfg[name]
          cfg[name] = new Array()
          cfg[name][cfg[name].length] = val
        }
      }
    }
    if (uavDelList) {
      for (i = 0; i < uavDelList.length; i++) {
        name1 = uavDelList[i].substring(0, uavDelList[i].indexOf('='))
        val = uavDelList[i].substring(uavDelList[i].indexOf('=') + 1)
        if (isArray(cfg[name1])) {
          for (var j = 0; j < cfg[name1].length; j++) {
            if (cfg[name1][j] == val)
	     delete cfg[name1][j];
          }
          compressArray(cfg[name1])
        } else if (cfg[name1] == val)
          cfg[name1] = ''
      }
    }
    if (uavSetList) {
      for (i = 0; i < uavSetList.length; i++) {
        name = uavSetList[i].substring(0, uavSetList[i].indexOf('='))
        val = uavSetList[i].substring(uavSetList[i].indexOf('=') + 1)
        cfg[name] = val
      }
    }
  }
  uavAddList = null
  uavDelList = null
  uavSetList = null
  if (state == 'init' || state == 'load') {
    for (i = 0; i < defaults.length; i += 2) {
      if (!cfg[defaults[i]] && defaults[i] != 'mailAutoReplyTextInternal' && defaults[i] != 'mailAutoReplyText' && defaults[i] != 'mailAutoReplyTimeout' && defaults[i] != 'mailAutoReplySubject')
        cfg[defaults[i]] = defaults[i + 1]
    }
  }
///////AK SMIME  NOv 21//////

if(applet_loaded==false &&cfgFrame.smimeEnabled==true){
load(appletFrame,srcHREF + 'applet_fs.html');applet_loaded=true;
}
///////AK NOv 21//////
  refreshLang()
  refreshColorSet()
  found = false
  for (i = 0; i < cfgFrame.mbox.length; i++) {
    if (cfgFrame.mbox[i].name == mboxFrame.mbox) {
      found = true
      if (cfgFrame.mbox[i].msgs == 0)
        sortid = new Array()
      break
    }
  }
  for (i = 0; i < cfgFrame.sub.length; i++) {
    if (cfgFrame.sub[i].name == mboxFrame.mbox) {
      found = true
      if (cfgFrame.sub[i].msgs == 0)
        sortid = new Array()
      break
    }
  }
  if (!found) {
    sortno = -1
    sortid = new Array()
    mboxFrame.mbox = null
  }
  eval(cfgOp)
  cfgOp = ''

  if(crumbUpdateNeeded)
    refreshBreadCrumb()

  if (state == 'load') {
    var cmdstr = ''

    loaded = true
    if (!isFldr('INBOX')) {
        cfg['meSentFolder'] == ''
        cfg['meTrashFolder'] == ''
    } else if (cfg['meInitialized'] || (meInitialized == 'true') ) {
      if (cfg['meDraftFolder'] && !isFldr(cfg['meDraftFolder']))
        cmdstr += (cmdstr.length > 0 ? '&argv=' : '&mbox=') +
          encode(cfg['meDraftFolder'])
      if (cfg['meSentFolder']) {
        if (!isFldr(cfg['meSentFolder']))
          cmdstr += (cmdstr.length > 0 ? '&argv=' : '&mbox=') +
            encode(cfg['meSentFolder'])
      } else if (!isFldr(i18n['sent folder'])) {
          cmdstr += (cmdstr.length > 0 ? '&argv=' : '&mbox=') +
            encode(i18n['sent folder'])
      }
      if (cfg['meTrashFolder']) {
        if (!isFldr(cfg['meTrashFolder']))
          cmdstr += (cmdstr.length > 0 ? '&argv=' : '&mbox=') +
            encode(cfg['meTrashFolder'])
      } else if (!isFldr(i18n['trash folder'])) {
          cmdstr += (cmdstr.length > 0 ? '&argv=' : '&mbox=') +
            encode(i18n['trash folder'])
      }
      if (cmdstr.length > 0)
        cmdOp = 'refreshCfg()'
    } else {
      cmdstr = initAccount()
    }
    if (cmdstr.length > 0) {
      cmdstr = '&cmd=create' + cmdstr
      load(cmdFrame, msgHREF + 'cmd.msc?sid=' + sid + cmdstr)
      return
    }

    sortOrder = cfg['meSortOrder']
    orgSort = sortOrder
    if (initialMbox != null) {
      refreshMbox(initialMbox)
    } 
    else if (cfgFrame.mbox.length == 0) {
      refreshMbox('')
    } else {
      refreshMbox('INBOX')
    }
  } else if (state == 'folders') {
	if (main.beInComp == true) {
        return;
      }
    i = folderRefresh
    folderRefresh = false
    displayFolders(i)
  } else if (state == 'options') {
    setColor()
    if (cfgFrame.errno == 0) {
      if (mailFrame.toolFrame)
        mailFrame.refresh()
      else
        selectOptions()
    }
  }
  submitted=false;
}

function msgCB() {
  if (isRefreshing() || mboxFrame.flag == null)
    return
  if (msgFrame.errno != 0) {
    alert(msgFrame.errstr)
    return
  }
  if (msgFrame.uid != 0) {
    if (((mboxFrame.mbox).toLowerCase()=='drafts')||(msgFrame.flags & mboxFrame.flag['\\draft']) ){
      compose('draft')
      return
    }
    if ((mboxFrame.msg[sortid[sortno]].flags &
      mboxFrame.flag['\\seen']) == 0) {
      mboxFrame.msg[sortid[sortno]].flags |= mboxFrame.flag['\\seen']
      mboxFrame.seen++
      if (getHeaderStr(msgFrame.hdr[0], 'disposition-notification-to') != '') {
	if (!mboxFrame.flag['$MDNSent'])
	  mboxFrame.flag['$MDNSent'] = Math.pow(2, mboxFrame.flag.length - 1)
	if ((mboxFrame.msg[sortid[sortno]].flags & mboxFrame.flag['$MDNSent']) == 0) {
	  receiptWindow = new Window(srcHREF + 'receipt_fs.html?' + clientargs(),
	    'receiptWindow' + unique++, 'status,width=620,height=20')
	}
      }
    }
    if (state == 'msg') {
      if (mailFrame.toolFrame)
        mailFrame.refresh()
    } else {
      state = 'msg'
      load(mailFrame, srcHREF + 'msg_fs.html')
    }
  }
}

function mboxCB() {

  if(mboxFrame.errno != 0)
  {
     alert(mboxFrame.errstr)
     displayFolders();
     return
  }

  if (isRefreshing())
    return

  if(searchForBody=='true') visitedMboxCB = 'true'


  sortno = mboxFrame.msg.length
  sortid = new Array(sortno)

  var i
  for (i = 0; i < sortno; i++)
    sortid[i] = i
if(mbox_from_msg>0) { display_msg();return; } 

  if (initialMsg != null) {
      displayMbox(false)
      if (initialMbox == null) {
        selectUid(initialMsg)
      } else {
        selectUid(initialMsg, initialMbox)
      }
      initialMsg = null
      initialMbox = null
  } 
  else if (state == 'mbox' && mailFrame.displayMbox) {
    if (mailFrame.toolFrame && oldMbox == mboxFrame.mbox)
      displayMbox(true) 
    else
      displayMbox(false) 
  }
  else if (mboxFrame.mbox != '') 
      displayMbox(false) 
  else 
      displayFolders();
}

function timeoutCB() {
  if (shutdown != 'logout')
    alert(i18n['timeout'])
  exit()
}

function nframe(n, p) {
  return '<frame name="' + n + '" noresize scrolling="no" src="' +
         p  + '/frame.html?' + clientargs() + '">'
}

function nbutton(n1, n2, f, w, c) {
  var cn = (c ? c : 'Btn1')
  var s = '<input class="' + cn + '" type=button name="' + n1 +
          '" value="' + n2 + 
          (w ? '" width="' + w : '') + '" onClick="' + f + 
          '" onMouseOver="this.className=\''+cn+'Hov\'" onFocus="this.className=\''+cn+'Hov\'" onMouseOut="this.className=\''+cn+'\'" onBlur="this.className=\''+cn+'\'">'
  return s
}

function ntable(b, cp, cs, cl, w, bg) {

  return '<table ' + (cl ? 'class="' + cl + '"' : '') + 
         ' border=' + b + ' cellpadding=' + cs + 
         ' cellspacing=' + cs + ' width=' + (w ? w : '100%') + 
         (bg ? 'bgcolor="' + bg + '"' : '') + '>\n'
}

function button(l, f, tool) {
  var s = '<table border=0 cellspacing=0 cellpadding=0>\n' +
    '<tr bgcolor=' + chrome0 + '>\n' +
    '<td><table border=0 cellspacing=1 cellpadding=' +
    (NN >= 3 && NN < 4 ? 1 : 0) + ' width=100%>' +
    '<tr align="center" bgcolor="' + (tool ? accent2 : chrome1) +
    '"><td nowrap><nobr>'

  if (f)  
    s += '<a id="' +
      (tool ? 'blacklink' : 'whitelink') +
      '" href="javascript:' + f +
      '" onMouseOver="return hint(\'' +
      (l.indexOf('"') == -1 ? i18n_squote(l) : '') +
      '\')" onMouseOut="return hint()">' + font(tool ? 1 : 2, tool ? black : white)
  else
    s += font(tool ? 1 : 2, chrome1)
  s += nbsp + html(l) + nbsp + '</font>'
  if (f)  
    s += '</a>'
  s += '</nobr></td></tr></table></td></tr></table>\n'
  return tool ? s : '<td>' + s + '</td>'
}

function WMtoolbar() {
  var argv = WMtoolbar.arguments
  var s = ''
  var enable
  var td = '<td nowrap>'
  var image = cfg['meToolImage'] != 'false'
  var text = cfg['meToolText'] != 'false'
  var textonly = text && !image
  var sz = 2 + (textonly ? 1 : 0)

  setColor()
  for (var i = 0; i < argv.length; i += 6) {
    enable = argv[i + 5]
    s += td
    if (enable && !textonly)
      s += '<a' + (textonly ? '' : ' id="blacklink"') +
        ' href="javascript:' + argv[i + 1] +
	'" onMouseOver="return hint(\'' + i18n_squote(argv[i]) +
	'\')" onMouseOut="return hint()">'
    if (image) {
      if (argv[i]) {
	s += '<img src="' + argv[i + 2] + '" border=0 hspace=4 vspace=0'
	if (!text)
	  s +=' alt="' + argv[i] + '"'
	if (argv[i + 3] > 0)
	  s += ' width=' + argv[i + 3]
	if (argv[i + 4] > 0)
	  s += ' height=' + argv[i + 4]
	s += '>'
      } else {
        s += '<img src="' + argv[i + 2] + '" hspace=3 vspace=0'
	if (argv[i + 3] > 0)
	  s += ' width=' + argv[i + 3]
	if (argv[i + 4] > 0)
	  s += ' height=' + argv[i + 4]
	s += '>'
      }
    }
    if (text) {
      if (argv[i]) {
        if (image)
	  s += '<br>'
	if (textonly) {
	  s += button(argv[i], enable ? argv[i + 1] : null, true)
	} else {
	  s += '<nobr>'
	  if (enable)
	    s += font(sz, (textonly ? null : black),'verdana,geneva,Helvetica,Arial,sans-serif')
	  else
	    s += font(sz, chrome1,'verdana,geneva,Helvetica,Arial,sans-serif')
	  s += argv[i]
	  s += '</font></nobr>'
	}
      } else if (!image) {
        s += '|'
      }
    }
    if (enable && !textonly)
      s += '</a>'
    s += '</td>\n'
  }
  return s
}

function collect() {
  collectWindow = new Window(srcHREF + 'collect_fs.html?'+clientargs(),
  'collectWindow' + unique++, 'resizable,' +
  (mac ? 'width=280,height=180' : 'width=400,height=250'))
}

function compose(type, s) {
  if (!curPab)
    fetchPab();
  var h = 640;

  if( screen.height <= 600)
    h = screen.height - 20;
  else if( IE > 4 )
      h = 700;
  var w = ((IE >= 4 || NN >= 4) && screen.width > 640) ? 740 : 640

  if (mac || sun) {
      h = 530
      w = 680
  }

  if (!cfg['mail']) {
    alert(i18n['no mail'])
    return
  }
  if(!s || getArg('fromSearch',s) == null)
    compose_type = type

  // done since resizable option is making the window go blank under 4.7x versions //
  // once we find out the reason will take it out //
  if(NN > 4 && NN < 5 && sun) 
   resize = "resizable=false"; 
  else
   resize = "resizable=yes";

  if (type == 'draft' && draftHdl) {
    draftHdl.refresh()
  } else {
   cmdOp = 'composeWindow = new Window("' + srcHREF + 'comp_fs.html?' +
       clientargs() + (s ? '&' + s : '') + '", "composewindow' + unique++ + '", "' +
       resize + ', width=' + w + ' ,height=' + h + '")'
   load(cmdFrame, msgHREF + 'cmd.msc?cmd=noop&sid=' + sid)
  }
}


function setfolderpermission(foldername,acl,ispersonal) {
   var h = ((IE >= 4 || NN >= 4) && screen.height > 480) ? 350 : 550
   var w = ((IE >= 4 || NN >= 4) && screen.width > 640) ? 650 : 640
 
   if (mac) {
     h = 400
     w = 540
   } else if (IE >= 4 && screen.width > 640) {
     w = 740
   }
   folderpermission = foldername
   folderacl = acl
   isfolderprivate = ispersonal
   acl = split(acl,'\t')
   var uid;
   if(cfgFrame.mailDomain != cfgFrame.defaultdomain)
      uid = cfg['uid'] + '@' + cfgFrame.mailDomain
   else
      uid = cfg['uid']
   for(var i =0; i < acl.length; i = i+2)
    {
       if((acl[i] == uid) || (acl[i] == 'anyone'))
       {
             for(var j = 0; j< acl[i+1].length; j++)
               {
                   if(acl[i+1].charAt(j) == 'a')
                    {
 
                          folderPermissionWindow = new Window(srcHREF + 'setpermission_fs.html?'+main.clientargs(),
                            'folderPermissonWindow', 'width=' + w +',height=' + h)
                          if( IE >= 4) folderPermissionWindow.opener = self;
                          return
                    }
               }
      }
    }
    alert(i18n['SetPermissions nopermissionslaert'])
 }

function subscribeFolder()
{
  var h = ((IE >= 4 || NN >= 4) && screen.height > 480) ? 400 : 350
  var w = ((IE >= 4 || NN >= 4) && screen.width > 640) ? 650 : 600

  if (mac) {
    h = 400
    w = 540
  } else if (IE >= 4 && screen.width > 640) {
    w = 650
  }

   SubscribeWindow = new Window(srcHREF + 'subscribe_fs.html?'+main.clientargs(),'SubscribeWindow', 'resizable,width=' + w +',height=' + h)
    if( IE >= 4) SubscribeWindow.opener = self;
}

function cidToPartNumber(part, contentID) {
  for (i = 0; i < msgFrame.part.length; i++) {
    if (part[i].hdr['content-id'] == contentID)
      return part[i].number
  }
  return -1
}

function getBody(bg, isColor, tx, lk, vlk, alk, x, y) {
  var s = '<body'

  s += (isColor ? ' bgcolor=' + bg : ' background="' + bg + '"')
  s += ' text=' + ((tx == null || tx == '' || tx == 'default') ? black : tx)
  s += ' link=' + (lk ? lk : link0) + ' vlink=' + (vlk ? vlk : link0) +
    ' alink=' + (alk ? alk : link0)
  if (NN >= 4) {
    if (x && y)
      s += ' marginwidth=' + x + ' marginheight=' + y
    else
      s += ' marginwidth=0 marginheight=0'
  }
  return s + '>\n'
}

function pageTo(num) {
  d_from = num
  if (searched == 1)
    refreshMbox(mboxFrame.mbox, s_search, s_hold)
  else
    refreshCurrMbox()
}

function pageForward() {
  d_from = d_to
  if (searched == 1)
    refreshMbox(mboxFrame.mbox, s_search, s_hold)
  else
    refreshCurrMbox()
}

function pageBack() {
var st=mboxFrame.start;
d_from = st - parseInt(cfg['meViewSize'])
  if (d_from < 0)
    d_from = 0
  if (searched == 1)
    refreshMbox(mboxFrame.mbox, s_search, s_hold)
  else
    refreshCurrMbox()
}

// user administration utilities
function unescape_crlf(s) {
  s = split(s, '');
  for (var i = 0; i < s.length; i++) {
    if (s[i] == '$') {
      s[i] = crlf;
    } else if (s[i] == '\\') {
      // \24 -> $
      if (s[i + 1] == '2' && s[i + 2] == '4')
        s[i] = '$';
      // \3a -> :
      else if (s[i + 1] == '3' && s[i + 2] == 'a')
        s[i] = ':';
      // \22 -> "
      else if (s[i + 1] == '2' && s[i + 2] == '2')
        s[i] = '"';
      // \7c -> |
      else if (s[i + 1] == '7' && s[i + 2] == 'c')
        s[i] = '|';
      // \25 -> %
      else if (s[i + 1] == '2' && s[i + 2] == '5')
        s[i] = '%';
      // \5e -> ^
      else if (s[i + 1] == '5' && s[i + 2] == 'e')
        s[i] = '^';
      // \5c -> \
      else if (s[i + 1] == '5' && s[i + 2] == 'c')
        s[i] = '\\';
      // \28 -> (
      else if (s[i + 1] == '2' && s[i + 2] == '8')
        s[i] = '(';
      // \29 -> )
      else if (s[i + 1] == '2' && s[i + 2] == '9')
        s[i] = ')';
      else
        continue;
      s[i + 1] = s[i + 2] = '';
      i += 2;
      continue;
    }
  }
  return join(s, '');
}

function escape_crlf(s) {
  s = split(s, '');
  for (var i = 0; i < s.length; i++) {
    // $ -> \24
    if (s[i] == '$')
      s[i] = '\\24';
    // crlf -> $
    else if (s[i] == '\r') {
      s[i] = '$';
      if (s[i + 1] == '\n') {
        s[i + 1] = '';
        i++;
      }
    } else if (s[i] == '\n')
      s[i] = '$';
    // : -> \3a
    else if (s[i] == ':')
      s[i] = '\\3a';
    // " -> \22
    else if (s[i] == '"')
      s[i] = '\\22';
    // | -> \7c
    else if (s[i] == '|')
      s[i] = '\\7c';
    // % -> \25
    else if (s[i] == '%')
      s[i] = '\\25';
    // ^ -> \5e
    else if (s[i] == '^')
      s[i] = '\\5e';
    // \ -> \5c
    else if (s[i] == '\\')
      s[i] = '\\5c';
    // ( -> \28
    else if (s[i] == '(')
      s[i] = '\\28';
    // ) -> \29
    else if (s[i] == ')')
      s[i] = '\\29';
    else
      continue;
  }
  return join(s, '');
}

function escape_ldapfilter(s) {

  s = escape_crlf(s);

  s = split(s, '');
  for (var i = 0; i < s.length; i++) {
    // \ -> \5c
    if (s[i] == '\\')
      s[i] = '\\5c';
    // ( -> \28
    else if (s[i] == '(')
      s[i] = '\\28';
    // ) -> \29
    else if (s[i] == ')')
      s[i] = '\\29';
    else if (s[i] == '*')
      s[i] = '\\2A';
    else
      continue;
  }
  return join(s, '');
}





function unescape_sepchar(str) {
  var a, s

  a = split(str, '\\3a')
  s = join(a, ':')
  return s

}

function escape_sepchar(str) {
  var a, s

  a = split(str, ':')
  s = join(a, '\\3a')
  return s
}

function escape_js(s) {
  s = split(s, '');
  for (var i = 0; i < s.length; i++) {
    if (s[i] == '\\')
      s[i] = '\\\\';
    else if (s[i] == '\'')
      s[i] = '\\\'';
    else
      continue;
  }
  return join(s, '');
}

function getUserAttrIndex(name) {
  for (var i = 0; i < cfgFrame.usrattrval.length; i++) {
    if (name == cfgFrame.usrattrval[i].name)
      return i
  }
  return -1
}

function getUserAttrValue(name, idx) {
  var i, a, v

  for (i = 0; i < cfgFrame.usrattrval.length; i++) {
    a = cfgFrame.usrattrval[i].name
    if (a == name) {
      if (idx >= cfgFrame.usrattrval[i].vals.length)
        return ''
      v = cfgFrame.usrattrval[i].vals[idx]
      return unescape_crlf(v)
    }
  }
  return ''
}

function isUserAttrReadonly(name) {
  if (NN >= 3 && NN < 4)
    cfgFrame.form = cfgFrame.document.form
  for (var i = 0; i < cfgFrame.usrattrval.length; i++) {
    if (cfgFrame.usrattrval[i].name == name)
      return cfgFrame.usrattrval[i].readonly
  }
  return false
}

var uavAddList, uavDelList, uavSetList;

function addUserAttrValue(name, value) {
  var i
//Added the line below Bala
  if(value=='' || value==null) return

  var add = name + '=' + escape_crlf(value)
  var del = cfgFrame.form.del_attrs.value

  if (name.length <= 0)
    return
  if (isUserAttrReadonly(name)) {
    alert(i18n['readonly'] + ': ' + name)
    return
  }
  cfgFrame.form.add_attrs.value += add + ':'
  i = del.indexOf(add)
  if (i != -1) {
    var head, tail
    
    head = del.substring(0, i)
    i = del.indexOf(':', i)
    if (i != -1)
      tail = del.substring(i + 1, del.length)
    cfgFrame.form.del_attrs.value = del = head + tail
  }
  // track prefs changes in memory
  if (!uavAddList)
    uavAddList = new Array()
  uavAddList[uavAddList.length] = add
  // make sure the deleted pref is not also a deleted pref
  if (uavDelList) {
    for (var i = 0; i < uavDelList.length; i++) {
      if (uavDelList[i] == add) {
        uavDelList[i] = ''
      }
    }
    compressArray(uavDelList)
  }
}

function delUserAttrValue(name, value, noescape) {
  var del = name + '=' + (noescape ? value : escape_crlf(value))
  if (name.length <= 0)
    return
  else if (isUserAttrReadonly(name) == 1)
    alert(i18n['readonly'] + ': ' + name)
  else {
    cfgFrame.form.del_attrs.value += del + ':'

    // track prefs changes in memory
    if (!uavDelList)
      uavDelList = new Array()
    uavDelList[uavDelList.length] = del
  }
}

function pruneUserAttrValue(name) {
  var attr = null

  for (var i = 0; i < cfgFrame.usrattrval.length; i++) {
    if (name == cfgFrame.usrattrval[i].name) {
      attr = cfgFrame.usrattrval[i]
      break
    }
  }
  if (attr != null) {
    for (var i = 0; i < attr.vals.length; i++) 
      delUserAttrValue(attr.name, unescape_crlf(attr.vals[i]))
  }  
}

function setUserAttrValue(name, value, noescape) {
  var set = name + '=' + value
  var escSet = name + '=' + (noescape ? value : escape_crlf(value))
  if (name.length <= 0)
    return
  else if (isUserAttrReadonly(name))
    alert(i18n['readonly'] + ': ' + name)
  else {
    cfgFrame.form.set_attrs.value += escSet + ':'

    // track prefs changes in memory
    if (!uavSetList)
      uavSetList = new Array()
    uavSetList[uavSetList.length] = set
  }
}

function submitUserAttrChanges() {
  var i, s
  var form = cfgFrame.form

  s = form.add_attrs.value
  if (s.length > 1)
    form.add_attrs.value = s.substring(0, s.length - 1)
  s = form.del_attrs.value
  if (s.length > 1)
    form.del_attrs.value = s.substring(0, s.length - 1)
  s = form.set_attrs.value
  if (s.length > 1)
    form.set_attrs.value = s.substring(0, s.length - 1)
  form.cmd.value = 'setAttrs'
  form.sid.value = sid
  form.security.value = security
  form.submit()
}

function submitNewPassword(oldpw, newpw) {
  var form = cfgFrame.form

  cfgOp = 'alert(i18n["pass changed"])'
  form.cmd.value = 'changePassword'
  form.oldPassword.value = oldpw
  form.newPassword.value = newpw
  form.sid.value = sid
  form.security.value = security
  form.submit()
}

function setFrames() {
  if (NN >= 3 && NN < 4) {
    cfgFrame = self.frames[0]
    mboxFrame = self.frames[1]
    cmdFrame = self.frames[2]
    msgFrame = self.frames[3]
    mailFrame = self.frames[4]
  }
}

function isRefreshing(frame) {
  var refresh = false

  if (refreshing)
    refresh = true
  else if (self.cfgFrame == null ||
    self.cmdFrame == null || 
    self.mboxFrame == null || 
    self.msgFrame == null || 
    self.mailFrame == null ||
    self.pabFrame == null)
    refresh = true
  else if (mac && NN >= 4.0 && NN < 4.5 && cfgFrame.mbox == null)
    refresh = true
  else if (state == 'init' &&
    (cfgFrame.errno != null ||
     cmdFrame.errno != null ||
     mboxFrame.errno != null ||
     msgFrame.errno != null ||
     pabFrame.errno != null))
    refresh = true
  if (refresh) {
    refreshing = true
  } else {
    setFrames()
    if (!frame && state != 'init' && state != 'load')
      setColor()
  }
  return refresh
}

function getHeader(h, name) {
  var i, result = new Array()

  for (i = 0; h && i < h.length; i++) {
    if (h[i].name.toLowerCase() == name)
      result[result.length] = h[i].value
  }
  return result
}

function getHeaderStr(h, name) {
  var i, result = ''

  for (i = 0; h && i < h.length; i++) {
    if (h[i].name.toLowerCase() == name) {
      if (result != '')
        result += ', '
      result += h[i].value
    }
  }
  return result
}

function noaction() {
  load(cmdFrame, srcHREF + 'frame.html?bgcolor=' + accent1)
}

function help(num) {
var url = srcHREF + lang + '/help.htm?' + clientargs()

  if (num > 0)
    url += '#' + num ; 
  helpWindow = new Window(url,
    'helpWindow', 'status,resizable,scrollbars,width=620,height=433')
}

function mbox_label() {
  var s

  if (srch != '')
    return i18n['search results']
  if (mboxFrame.mbox == null || mboxFrame.mbox == '')
    s = fldr['INBOX']
  else if (fldr[mboxFrame.mbox])
    s = fldr[mboxFrame.mbox]
  else
    s = mboxFrame.mbox.substring(mboxFrame.mbox.lastIndexOf('/') + 1, mboxFrame.mbox.length)
  if (s.length > 15)
    return s.substring(0, 11) + '...'
  else
    return s
}

function isSpecialFolderState(name) {
  return (name == 'Inbox' || name == 'Sent' || name == 'Drafts' || name == 'Trash');
}

function mapStateToFolder(st) {
  switch(st) {
    case 'Inbox' : case 'INBOX' : return i18n['INBOX'];
    case 'Sent': return i18n['sent folder'];
    case 'Drafts': return i18n['draft folder'];
    case 'Trash': return i18n['trash folder'];
    default:
       return st;
  }
}

function mapFolderToState(f) {
  switch(f) {
    case i18n['INBOX'] : return 'Inbox';
    case i18n['sent folder'] : return 'Sent';
    case i18n['draft folder'] : return 'Drafts';
    case i18n['trash folder'] : return 'Trash';
    default:
       return 'mbox';
  }
}

function displaySpecialMbox(name) {
 var key = 'me' + name + 'Folder';                                              
 if(name == 'Drafts') key = 'meDraftFolder';                                    
 var mboxname = cfg[key] ? cfg[key] : name;  
 

 if(name=='Trash') {
   mboxname = cfg[key] ? cfg[key] : (cfg['mePrevTrash'] ? cfg['mePrevTrash'] : name);
 }

 if(name=='Inbox'){
   mboxname = 'INBOX';
 }

 if(isSpecialFolderState(name)) 
   state = name;
 else
   state = 'mbox'; 

 if(mboxname == mboxFrame.mbox)
    d_from = mboxFrame.start
 else
    d_from = 0
 
 refreshMbox(mboxname);
}

function tab(label, isSelected, func, f) {
  
  var s = '<td width=1%'

  if (isSelected)
    s += ' bgcolor=' + chrome2
  s += ' nowrap><nobr>' + nbsp
  if (isSelected)
    s += font(2, black,'verdana,geneva,Helvetica,Arial,sans-serif')
  else if (func == null)
    s += font(2, chrome2,'verdana,geneva,Helvetica,Arial,sans-serif')
  else
    s += '<a id="whitelink" href="' + (f ? '' : 'javascript:main.') + func +
      '" target="' + (f ? f : 'mailFrame') + '" onMouseOver="return hint(\'' + 
      (label.indexOf('"') == -1 ? i18n_squote(label) : '') +
      '\')" onMouseOut="return hint()">' + font(2, white,'verdana,geneva,Helvetica,Arial,sans-serif')
  s += '<b>' + html(label) + '</b>'
  if (!isSelected && func != null)        
    s += '</a>'
  return s + nbsp + '</font></nobr></td>\n'
}

function BreadCrumb(label, link) {
  this.label = label;
  this.link = link;
}

function getBreadCrumb() {
  var s =nbsp+ nbsp+ cfg['mail'] + ':' + nbsp;

  if(breadCrumbList[0] == null) {
    initBreadCrumb(fldr['INBOX'],'main.check_mail=1;main.refreshMbox()');
  }

  if(lastFolderisSpecial) {
    s += '<B>' + breadCrumbList[0].label + '</B>';
  }
  else {

    for(i=0;i < lastBreadCrumb;i++) {
      if(breadCrumbList[i].link != null && breadCrumbList[i].link != '')
        s += '<A href="javascript:'+ breadCrumbList[i].link + '"'+' target="mailFrame">' 
          + breadCrumbList[i].label + '</A>' + nbsp + '&gt;'+ nbsp ;
      else 
        s += breadCrumbList[i].label + nbsp + '&gt;'+ nbsp ;
    }

    if(lastBreadCrumbActive) {
      s +=  '<A href="javascript:'+ breadCrumbList[i].link + '"'+' target="mailFrame">' + 
           breadCrumbList[i].label + '</A>';
    }
    else {
      s += '<B>' + breadCrumbList[i].label + '</B>';
    }
  }

  return  '<table border=0 cellspacing=0 cellpadding=0 width=100%>\n' +
    '<tr align="left">\n<td bgcolor="#cccccc" height="25">' + s + '</td></tr>\n' +
     '<tr><td bgcolor="#999999"><img src="imx/spacer.gif" width="1" height="1"></td></tr></table>'


}

function getMboxIndex(name) {
  var persf = main.cfgFrame.mbox
  var subf = main.cfgFrame.sub
  var lastcomp,i,j

  for(i=0;i < persf.length;i++) {
    if(mboxEquals(name,persf[i].name)){
      if((persf[i].flags & main.cfgFrame.flag['\\noselect']))
      	return -1;
      else 
      	return i
    }
  }

  for(j=0;j < subf.length;j++,i++) {
    if(mboxEquals(name,subf[j].name)){
    	if((subf[j].flags & main.cfgFrame.flag['\\noselect']))
        	return -1;
      	else
        	return i
        }
  }

  return -1  // execution should never reach here
}  

function getComponentFolders(mbox) {
  var comps
  var i = 0
  var prev = 0
  var end

  if(mbox == null || mbox.length == 0) return mbox;

  comps = new Array()
  while(true) {
    end = mbox.indexOf('/',prev)
    if(end == -1) {
      comps[i] = mbox.substring(0,mbox.length)
      return comps
    }
    comps[i] = mbox.substring(0,end)
    prev=end+1
    i++
  }
}

function constructBreadCrumb(mbox, isNextFolder, isSpecial) {
  var comps
  if(!isNextFolder) {
    if(lastFolderisSpecial)
      lastBreadCrumbActive = false;
    else
      lastBreadCrumbActive = true;

    return;
  }

  if(isSpecial != null)
    lastFolderisSpecial = isSpecial;

  lastBreadCrumb = -1;
  breadCrumbList = new Array();
  comps = getComponentFolders(mbox);
  for(i=0;i < comps.length;i++) {
    cfld = comps[i]
    ind = getMboxIndex(cfld);
    lastcomp = cfld.substring(cfld.lastIndexOf('/')+1,cfld.length)
    if(ind == -1)
    	appendBreadCrumb(lastcomp,'');
    else
    	appendBreadCrumb(lastcomp,'main.selectMbox(' + ind + ')');
  }
  lastBreadCrumbActive = false;

}
  
function appendBreadCrumb(label, func) {
  var bc = new BreadCrumb(label, func)
  breadCrumbList[++lastBreadCrumb] = bc;
}

function initBreadCrumb(label, func) {
  lastBreadCrumb = -1;
  appendBreadCrumb(label, func);
  currentlyFolder = true;
  lastBreadCrumbActive = false;
}

function updateBreadCrumb(delPath)
{
  var folderToDelete = delPath[delPath.length - 1];
  var crumbLength = breadCrumbList.length;

  crumbUpdateNeeded = false;

  for(i=0; i < crumbLength; i++)
    if(folderToDelete == breadCrumbList[i].label)
    {
      crumbUpdateNeeded = true;
      deletedFolder = delPath;
      return;
    }
  
  crumbUpdateNeeded = false;
}

function refreshBreadCrumb()
{
  crumbUpdateNeeded = false; // reset flag first

  // The updated breadCrumb should show that folder (and its ancestors)
  // such that the folder is the nearest ancestor to the deleted folder
  // and is selectable (i.e., has a link.

  var currentCrumb = "";

  for(i=0; i < breadCrumbList.length; i++)
    if(i != breadCrumbList.length - 1)
      currentCrumb += breadCrumbList[i].label + "/";
    else
      currentCrumb += breadCrumbList[i].label;

  // See if we can find a folder that matches the above said criteria.
  // To do this, we find a substring in 'currentCrumb'
  // which matches the appropriate mbox.

  // Check for local mbox
  var mboxToDisplay = findMatchingMbox(cfgFrame.mbox, currentCrumb);
  // Check for subscribed folders
  if(mboxToDisplay == "")
    mboxToDisplay = findMatchingMbox(cfgFrame.sub, currentCrumb);

  if(mboxToDisplay == "")
    constructBreadCrumb(fldr['INBOX'], true, true);
  else
    constructBreadCrumb(mboxToDisplay, true, false);
}

function findMatchingMbox(folderList, currentCrumb)
{
  var longestMatch = -1;
  var mboxToDisplay = "";

  for(i=0; i < folderList.length; i++)
  {
    if(folderList[i].name.length > currentCrumb.length)
      continue;
    var index = currentCrumb.indexOf(folderList[i].name);

    if(index == 0)
    {
      if(folderList[i].name.length > longestMatch && // nearest ancestor
          !(folderList[i].flags & cfgFrame.flag['\\noselect'])) // selectable
      {
        longestMatch = folderList[i].name.length;
        mboxToDisplay = folderList[i].name;
      }
    }
  }
  return mboxToDisplay;
}

function imagesoff() {
  document.userlogout.src = userlogoutoff.src;
}

// Function to 'turn-on' the target image.
function imageon(imgName) {
  formElement[imgName].src = eval(imgName + "on.src");
}

// Function to 'load the content page and swap tab images'.
function loadandswap(imgName, contentName) {
  imagesoff();
  imageon(imgName);
}
		
// Function to handle mouse overs
function over(imgName) {
  mailFrame.toolFrame.form[imgName].src= msgHREF + 'imx/red_dot2.gif'
}

// Function to handle mouse outs
function out(imgName) {
  mailFrame.toolFrame.form[imgName].src= msgHREF + 'imx/white_dot.gif'
}




function toolFrame() {
 if (isRefreshing())
    return ''
  var ieWidth = NN > 0 ? 40 : 30
  if(NN > 0) nnString = ''
  else
     nnString = '<TABLE border=0 cellspacing=0 cellpadding=0 width=100% height="0.1%">'+
  '<tr><td bgcolor="#CC0000" colspan="2" width="85%"><img src="imx/spacer.gif" width="1" height="5"></td>'+
  //'<td bgcolor="#ffffff" width="1"></td>'+
  '<td bgcolor="#CC0000"><img src="imx/spacer.gif" width="1" height="5"></td>'+
  '</tr></TABLE>\n'
  

  return getBody(chrome2, true) + '<form name="form">\n' +
  nnString +
  '<table border=0 cellspacing=0 cellpadding=0 width=100%>\n' +
  '<tr>\n' +
  '</tr><tr>\n' +
  '<TD width=1% nowrap bgcolor="'+ chrome1 +'"><NOBR><IMG src="imx/Banner.gif" width="273" height="27" alt="'+i18n['iplanet messenger express']+'" align=texttop border=0 hspace=5 vspace=3></nobr></TD>\n'+
  '<TD nowrap bgcolor="'+ chrome1 +'">'+ main.font() + '<NOBR>'+i18n_tab_header(cfg['cn'])+'</FONT></TD>\n'+
  '<TD align=center width='+ieWidth+'% nowrap bgcolor="'+ chrome1 +'"><NOBR><IMG src="imx/spacer.gif" vspace=2 width=1 height=27></NOBR></TD>\n'+
  //'<td bgcolor="#ffffff" width="1" height=27></td>\n'+
  '<td><a href="javascript:main.help()" onMouseOver="javascript:main.over(\'help\')" onMouseOut="javascript:main.out(\'help\')"><img name="help" src="imx/white_dot.gif" width="13" height="9" border="0"></a></td>\n'+
  '<td nowrap><a href="javascript:main.help()" onMouseOver="javascript:main.over(\'help\')" onMouseOut="javascript:main.out(\'help\')"><span class="banner-links">'+i18n['help']+'</span></a></td>\n'+
  '<td><img src="imx/spacer.gif" width="20" height="1"></td>\n'+
  '<td><a href="javascript:main.logout()" onMouseOver="javascript:main.over(\'userlogout\')" onMouseOut="javascript:main.out(\'userlogout\')"><img name="userlogout" src="imx/white_dot.gif" width="13" height="9" border="0"></a></td>\n'+
  '<td nowrap><a href="javascript:main.logout()" onMouseOver="javascript:main.over(\'userlogout\')" onMouseOut="javascript:main.out(\'userlogout\')"><span class="banner-links">'+i18n['logout']+'</span></a></td></tr>\n' +
  '</table>\n'+
  '<table border=0 cellspacing=0 cellpadding=0 width=100%>\n' +
  '<tr bgcolor=' + chrome0 + '>\n' +
   '<td>' +
   '<table border=0 cellspacing=1 cellpadding=1 width=100%>\n' +
   '<tr align="center" bgcolor="' + chrome1 + '">\n' +
   tab(i18n['folders'], state == 'folders', 'displayFolders()') +
   tab(fldr['INBOX'], state == 'Inbox' || state == 'init',
   cfgFrame.mbox.length + cfgFrame.sub.length == 0 ? null : 'displaySpecialMbox(\'Inbox\')') +
   tab(fldr['Sent'],state == 'Sent','displaySpecialMbox(\'Sent\')') +
   tab(fldr['Trash'],state == 'Trash','displaySpecialMbox(\'Trash\')') +
   tab(fldr['Drafts'],state == 'Drafts','displaySpecialMbox(\'Drafts\')') +
   (cfgFrame.pabEnabled ? tab(i18n['pab'], state == 'pab', 'displayPab()') : '') +
   tab(i18n['options'], state == 'options', 'selectOptions()') +
   '<td width=50%>' + nbsp + '</td>\n' +
   '</tr></table>\n' +
   '</td>\n' +
   '</tr></table>\n' +
   getBreadCrumb() +
   mailFrame.getToolbar() + '</form>'
}


function mailFrameHTML() {
  return '<table width=100% height=100%><tr><td align=center>' +
    font() + i18n['loading'] + '</font></td></tr></table>'
}

function start() {
  if (self.cfgFrame == null || self.mboxFrame == null || self.msgFrame == null) {
    timer = window.setTimeout('start()', 100)
  } else if (state == 'init') {
    setFrames()
    if (NN >= 3 && timer)
      clearTimeout(timer)
    state = 'load'
    refreshing = false
    refreshCfg()
  }
}

function compareNumber(a, b) {
   return a - b
}


function _sortArray(array, origiLo, origiHi, method) {
   var lo = origiLo
   var hi = origiHi
   var midval = (lo + hi == 1) ? array[0] : array[parseInt((lo + hi) / 2)]
 
   while (true) {
     while (lo < origiHi && method(array[lo], midval) < 0)
       lo++
     while (hi > origiLo && method(array[hi], midval) > 0)
       hi--
     if (lo < hi) {
       var tmp = array[lo]
 
       array[lo++] = array[hi]
       array[hi--] = tmp
     } else if (lo == hi) {
       lo++
       hi--
     } else {
       break
     }
   }
   if (origiLo < hi)
     _sortArray(array, origiLo, hi, method)
   if (lo < origiHi)
     _sortArray(array, lo, origiHi, method)
}

function _compareBy(a, b) {
   var s1 = a.toString()
   var s2 = b.toString()
 
   if (s1 < s2)
     return -1
   else if (s1 > s2)
     return 1
   return 0
}

function sort(array, func) {
   // built in funcs are 10x slower
   if (func == null)
     func = _compareBy
   if (array.length > 1)
     _sortArray(array, 0, array.length - 1, func)
}



// [=> PAB items
function ldapCB() {
}

// flag for first time login
var firstpab='false';

function pabCB() {
  if (isRefreshing())
    return;
  if(!pabFrame.pabs) return;
  // Because there's no error and there aren't any PABs,
  // we're probably using the PAB feature for the first time.
  // Add a PAB immediately.
  if (pabFrame.pab_cmd && firstpab == 'false' &&
    pabFrame.pab_cmd == 'PAB_CMD_GET_PABS' &&
    pabFrame.pabs.length < 1) {
    
    // set first time flag
    firstpab='true';

    pabAttrs = cloneObject(pabFrame.attrs);
    // NN 4.04: cloneObject dose not work, just copy
    if (!pabAttrs)
      pabAttrs = pabFrame.attrs;

    load(pabFrame, msgHREF + 'ldap.msc?sid=' + sid + '&ldapurl=pab&filter=' +
      encode('cmd=PAB_CMD_ADD_ENTRY|new=' +
        pabFrame.attrs.cn.name + ':' + i18n['default PAB'] + '\n' +
        pabFrame.attrs.objectclass.name + ':pab\n\n|'));
  } else if (pabFrame.pab_cmd && firstpab == 'true' && pabFrame.pabs &&
        pabFrame.pab_cmd == 'PAB_CMD_ADD_ENTRY' &&
        pabFrame.errno == 0 ) {
    // reset flag as the default pab created and we don't need another one
    firstpab = 'false';
    // set current pab and read in entries
    curPab =pabFrame.pabs[0].un;
    load(pabFrame, msgHREF + 'ldap.msc?sid=' + sid + '&ldapurl=pab&filter=' +
      encode('cmd=PAB_CMD_EDIT|pab=' + curPab + '|from=0|len=999|'));
  } else if (pabFrame.pab_cmd &&
    pabFrame.pab_cmd == 'PAB_CMD_GET_PABS') {
    // Grab a local copy of PAB attribute objects so we can use them later.
    pabAttrs = cloneObject(pabFrame.attrs);
    // NN 4.04: cloneObject dose not work, just copy
    if (!pabAttrs)
      pabAttrs = pabFrame.attrs;

    curPab = pabFrame.pabs[0].un;
    // We're not supporting multiple PABs yet, so just grab the first PAB
    // in the list and fetch its entries and groups
    load(pabFrame, msgHREF + 'ldap.msc?sid=' + sid + '&ldapurl=pab&filter=' +
      encode('cmd=PAB_CMD_EDIT|pab=' + curPab + '|from=0|len=999|'));
  } else {
   /*  if ((IE >= 4 || NN >= 3) && lookupWindow && !lookupWindow.isClosed()
      && lookupWindow.hdl.afterFetch)
      lookupWindow.hdl.afterFetch(); */
    if (state == 'pabinit') 
      sortPab(false, true);
//    displayPab();
  }

//Copy pabAttrs to some variable
if (main.pabFrame.people)
	updatePabFrame();

//Copy attributes and values for search
if (main.pabFrame.attrs)
 updatePabAttrList();
}

function fetchPab() {
  if (!cfgFrame.pabEnabled)
{ updatePabAttrList() ;    
    return;
}
  if (!curPab)
    load(pabFrame, msgHREF + 'ldap.msc?sid=' + sid + '&ldapurl=pab&filter=' +
      encode('cmd=PAB_CMD_GET_PABS|'));
  else
    load(pabFrame, msgHREF + 'ldap.msc?sid=' + sid + '&ldapurl=pab&filter=' +
      encode('cmd=PAB_CMD_EDIT|pab=' + curPab + '|from=0|len=999|'));
}

function displayPab() {
  // This only works if we assume that only two server requests will be
  // exectued in pabFrame (PAB_CMD_GET_PABS and PAB_CMD_ADD_ENTRY).
  if (pabFrame.errno != 0) {
    alert(pabFrame.errstr);
    return;
  }
  constructBreadCrumb(i18n['pab'],false);
  if (!pabFrame.pab_cmd || pabFrame.pab_cmd == 'PAB_CMD_ADD_ENTRY') {
    state = 'pabinit';
    fetchPab();
  } else {
    state = 'pab';
    if (mailFrame.location.href != srcHREF + lang + '/pab_fs.html?' + clientargs()) 
      load(mailFrame, srcHREF + lang + '/pab_fs.html');
    else
      mailFrame.refresh();
  }
}

/* t ... type {entry, group} to determine which array i indexes
 * i ... index
 */
function PabSortObj(t, i) {
  this.t = t;
  this.i = i;
  this.toString = function PSO__toString(){ return i };
}

/* sortPab --------------------------------------------------------------------
 * We have all the entries and groups for this PAB already, but they're sorted
 * separately by default. Combine the two, if necessary, and sort them.
 */
function sortPab(by, refresh) {
  var i, j, k;
  if (!pabSrtIdx || !by) {
    pabSrtIdx = new Array(main.pabFrame.people.length + main.pabFrame.groups.length);
    // NN 4.04: new Array(0) returns NULL, so create an object instead 
    if (!pabSrtIdx) {
      pabSrtIdx = new Object;
      pabSrtIdx.length = 0;
    }
    for (i = 0; i < main.pabFrame.people.length; i++)
      pabSrtIdx[i] = new PabSortObj(ENTRY, i);
    for (i = main.pabFrame.people.length; i < pabSrtIdx.length; i++)
      pabSrtIdx[i] = new PabSortObj(GROUP, i - main.pabFrame.people.length);
    sortPab(pabSrtBy, refresh);
    //main.sort(pabSrtIdx, pabByName);
    if (!pabSrtAsc) {
      sortPab(pabSrtBy, pabSrtAsc);
      pabSrtAsc = false;
    }
    displayPab();
    return;
  } // ELSE

  if (!refresh && pabSrtBy == by && pabSrtBy != BY_TYPE) {
    pabSrtAsc = !pabSrtAsc;
    for (i = 0; i < pabSrtIdx.length / 2; i++) {
      j = pabSrtIdx.length - i - 1;
      k = pabSrtIdx[i];
      pabSrtIdx[i] = pabSrtIdx[j];
      pabSrtIdx[j] = k;
    }
    if (mailFrame && mailFrame.afterSort)
      mailFrame.afterSort();
  } else {
    var reverse = pabSrtBy == BY_TYPE && pabSrtBy == by;
    pabSrtBy = by;
    if (!refresh)
      pabSrtAsc = true;
    
    if (by == BY_NAME)
      sort(pabSrtIdx, pabByName);

    if (by == BY_TYPE) {
      if (!reverse)
        sort(pabSrtIdx, pabByType);
      else {
        sort(pabSrtIdx, pabReverseByType);
        pabSrtBy = -1;
      }

    }
    if (by == BY_MAIL)
      sort(pabSrtIdx, pabByMail);
    if (mailFrame && mailFrame.afterSort)
      mailFrame.afterSort();
  }
}

function pabByName(a, b) {
  if (a.t == ENTRY) {
    var s1 = pabFrame.people[a.i].cn.toLowerCase();
  } else {
    var s1 = pabFrame.groups[a.i].cn.toLowerCase();
  }
  if (b.t == ENTRY) {
    var s2 = pabFrame.people[b.i].cn.toLowerCase();
  } else {
    var s2 = pabFrame.groups[b.i].cn.toLowerCase();
  }

  if (s1 < s2)
    return -1;
  else if (s1 > s2)
    return 1;
  return 0;
}

function pabByType(a, b, reverse) {
  if (a.t == ENTRY && b.t == GROUP)
    return !reverse ? 1 : -1;
  if (a.t == GROUP && b.t == ENTRY)
    return !reverse ? -1 : 1;
  if (a.t == b.t)
    return pabByName(a, b);
}

function pabReverseByType(a, b) {
  return pabByType(a, b, true);
}

function pabByMail(a, b) {
  var s1, s2;
  if (a.t == b.t) {
    if (a.t == ENTRY) {
      s1 = pabFrame.people[a.i].mail ? pabFrame.people[a.i].mail[0].toLowerCase() : '';
      s2 = pabFrame.people[b.i].mail ? pabFrame.people[b.i].mail[0].toLowerCase() : '';
    } else
      return pabByName(a, b);
  } else if (a.t == ENTRY &&
    (!pabFrame.people[a.i].mail || !pabFrame.people[a.i].mail[0]))
        return 1;
  else if (b.t == ENTRY &&
    (!pabFrame.people[b.i].mail || !pabFrame.people[b.i].mail[0]))
        return -1;
  else
    return pabByType(a, b, true);

  if (!s1 && !s2)
    return pabByName(a, b);
  else if (!s1)
    return 1;
  else if (!s2)
    return -1;
  if (s1 < s2)
    return -1;
  else if (s1 > s2)
    return 1;
  return pabByName(a, b);
}

function pabPageTo(num) {
  lastModUn = 0;
  pabPageHead = parseInt(num);
  lastModUn = pabPageTail = 0;
  displayPab(true);
}

function pabPageForward() {
  pabPageHead = pabPageTail;
  lastModUn = pabPageTail = 0;
  displayPab(true);
}

function pabPageBack() {
  pabPageHead -= parseInt(cfg['meViewSize']);
  lastModUn = pabPageTail = 0;
  if (pabPageHead < 0)
    pabPageHead = 0;
  displayPab(true);
}

function updatePabFrame(){
  for (i = 0; i < pabFrame.people.length; i++) {
    people[i] = pabFrame.people[i];
  }
  people.length = pabFrame.people.length;

  for (i = 0; i < pabFrame.groups.length; i++) {
    groups[i] = pabFrame.groups[i];
  }
  groups.length = pabFrame.groups.length;
}

function updatePabAttrList(){
  attr_list['cn'] = pabFrame.attrs ? pabFrame.attrs.cn.name : 'cn;lang-en' ;
  attr_list['givenname']=pabFrame.attrs?pabFrame.attrs.givenname.name:'givenname;lang-en' ; 
  attr_list['sn'] =pabFrame.attrs ? pabFrame.attrs.sn.name : 'sn;lang-en';
  attr_list['mail'] =pabFrame.attrs ? pabFrame.attrs.mail.name :'mail';
  attr_list['telephonenumber']=pabFrame.attrs?pabFrame.attrs.telephonenumber.name:'telephonenumber'; 
}

function selectMsg1(num)
{
if(mboxFrame.size==0)
{
state = 'mbox'
load(mailFrame, srcHREF + 'mbox_fs.html');
return;
}
 if (num==-1)
{
mbox_from_msg=1;
pageBack();
}
else if(num == -2)
{
 mbox_from_msg=4
 d_from = mboxFrame.start
 if (searched == 1)
    refreshMbox(mboxFrame.mbox, s_search, s_hold)
  else
    refreshCurrMbox()
}
else if(num == -3)
{
   mbox_from_msg=5
   pageForward()
}
else
selectMsg(num);
}            

function display_msg()
{
if(mbox_from_msg==13){
mbox_from_msg=0;
var f=(mboxFrame.mbox.toUpperCase()=='INBOX')?"INBOX":mboxFrame.mbox;
main.sortno=lastMessage[f].sortno;
main.selectMsg(main.sortno);
}
else if(mbox_from_msg==1 || mbox_from_msg == 4)
{
mbox_from_msg=0;
main.sortno=mboxFrame.count-1
main.selectMsg(main.sortno);
}
else if(mbox_from_msg==2 || mbox_from_msg == 5)
{
mbox_from_msg=0;
main.sortno=0
main.selectMsg(main.sortno);
}
}

function noop()
{


}   
