/********************************************
 *
 *UI related and can be shared by different HTML
 *
 ********************************************/
//Event funcs to highlight buttons
function evtSrc(e) {
  if (!e)
    var e=window.event
  var s = e.srcElement ? e.srcElement : e.target
  return s.nodeType==3 ? s.parentNode : s
}

function MM(e) {
  var s = evtSrc(e)
  if (s) s.className='ComBtnOver'
}
    
function MO(e) {
  var s = evtSrc(e)
  if (s) s.className='ComBtn'
}

function MM1(e) {
  var s = evtSrc(e)
  if (s) s.className='ComBtn1Over'
}
    
function MO1(e) {
  var s = evtSrc(e)
  if (s) s.className='ComBtn1'
}

function HL(e) {
  var r = null
  if (e.parentNode && e.parentNode.parentNode)
    r = e.parentNode.parentNode
  else if (e.parentElement && e.parentElement.parentElement)
    r = e.parentElement.parentElement
  if (r) {
    if (e.checked)
      r.bgColor= "#F5F8FF"
    else
      r.bgColor = "white"
  }
}

var _dobj = new Object()
_dobj.zIndex = 0
var IE = parent.IE
var NN = parent.NN

function _getX(e) {
  var x = 0
  if (IE)
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft
  if (NN)
    x = e.clientX + window.scrollX
  return x
}

function _getY(e) {
  var y = 0
  if (IE)
    y = e.clientY + document.documentElement.scrollTop
      + document.body.scrollTop
  if (NN)
    y = e.clientY + window.scrollY
  return y
}

function _getPN(n, m) {
  m = m ? m : 0;
  if (n > 400)
    return 405
  else
    return n > m ? n : m
}

function DS(e, id) {
  var el, x, y
  if (IE) e = window.event
  _dobj.node = evtSrc(e)
  _dobj.node.style.zIndex = ++_dobj.zIndex
  if (IE) {
    document.attachEvent("onmousemove", DG)
    document.attachEvent("onmouseup", DP)
    e.cancelBubble = true
    e.returnValue = false
  }
  if (NN) {
    document.addEventListener("mousemove", DG, true)
    document.addEventListener("mouseup", DP, true)
    e.preventDefault()
  }
}

function DG(event) {
  var x = _getX(event)
  var y = _getY(event)
  _dobj.node.style.left = _getPN(x, 5) + "px" //divider
  document.getElementById("left").style.width = _getPN(x-25, 5) //folder tree
  document.getElementById("right").style.left = _getPN(x, 10)+5 //right
//_dobj.node.style.top  = (_dobj.EST  + y - _dobj.CSY) + "%"
  if (IE) {
    window.event.cancelBubble = true
    window.event.returnValue = false
  }
  if (NN)
    event.preventDefault()
}

function DP(event) {
  if (IE) {
    document.detachEvent("onmousemove", DG)
    document.detachEvent("onmouseup", DP)
  }
  if (NN) {
    document.removeEventListener("mousemove", DG, true)
    document.removeEventListener("mouseup", DP, true)
  }
}

function nWMtoolbar(label, href, imgname, imgsrc, id, p, style) {
  p = p ? 'parent.' : ''
  id = id ? 'id="'+ id+ '" ' : ''
  if (href.indexOf('.msc')>0)
    href = '<a href="' + href + '" target="historyFrame">'
  else
    href = '<a href="javascript:' + href + '">'

  return '<span class="ComBtn" ' + id  + ' onMouseOver="this.className=\'ComBtnOver\'" ' + 
         'onMouseOut="this.className=\'ComBtn\'">' + href +
         '<img style="width: 16px; height: 16px; border: 0px" name="' + imgname + '" src="' + imgsrc +
         '" align="middle" ' +
         ' alt="' + label +
         '">'+ label + '</a></span>'
}

//Translates <i18n>string</i18n> to i18n['string']
function translate() {
  var k, v, list = document.getElementsByTagName("option")
  for (var i=0; i< list.length; i++) { 
    v = list.item(i)
    v = v.firstChild ? v.firstChild : v.nextSibling
    if (v.nodeValue.indexOf('i18n_') == 0) {
       k = v.nodeValue.substr(5)
       if (main.i18n[k])
          v.nodeValue = main.i18n[k]
    }
  }
  list = document.getElementsByTagName("select")
  for (var i=0; i< list.length; i++) { 
    v = list.item(i)
    k = v.selectedIndex
    v.selectedIndex = v.length -1
    v.selectedIndex = k
  }
  list = document.getElementsByTagName("i18n")
  for (var i=0; i< list.length; i++) { 
    v = list.item(i)
    v = v.firstChild ? v.firstChild : v.nextSibling
    if (main.i18n[v.nodeValue]) v.nodeValue = main.i18n[v.nodeValue]
  }
  
  list = document.getElementsByTagName("input")
  for (var i=0; i< list.length; i++) { 
    v = list.item(i)
    va = v.getAttribute("value")
    if (!va) continue
    if (va.indexOf('i18n_') == 0) {
      k = va.substr(5)
      if (main.i18n[k])
        v.setAttribute("value", main.i18n[k])
    }
  }
}


//508 compliance
FOEdebug = false

function FOEimg(f) {
  var list = document.getElementsByTagName("img")
  if (f)
    list = eval(f).document.getElementsByTagName("img")
  var title, alt, src, name, s
  for (var i=0; i< list.length; i++) {
    var v = list.item(i)
    src = v.getAttribute('src')
    if (src.indexOf('spacer') !=-1 ||src.indexOf('divider') !=-1 ) {
      v.setAttribute('alt', '')
      continue
    }
    title = v.getAttribute('title')
    alt = v.getAttribute('alt')
    name= v.getAttribute('name')
    if (!name && !alt & !title && FOEdebug) alert('Fix '+src) //manually fix it
    if (main.i18n[name]) s = main.i18n[name]
    if (title) s = title
    else if (alt) s = alt
    v.setAttribute('title', s)
    v.setAttribute('alt', s)
  }
}

function nTab(label, func, lnk, sel){
  var s ='' 

  var f = 'onMouseOver="return hint()" onMouseOut="return hint()" href="' + func +
    '" target="historyFrame">'

  if (main.state != 'msg'){
    if (sel)
      s += '<div class=Tab2Sel nowrap><span class=TabLblSel>' +
        label + '</span></div>'
    else
      s += '<div class=Tab2NotSel nowrap><a class=TabLblNormal ' +
        f + label + '</a></div>'
  } else { 
    if (!lnk && sel)
      s += '<div class=Tab2Sel nowrap><span class=TabLblSel>' +
        label + '</span></div>'
    else
      s += '<div class=Tab2NotSel nowrap><a class=TabLblSel ' +
        f + label + '</a></div>'
  }
  return s
}

function MboxURL(rname, ind, srch) {
  var s = main.msgHREF + 'history.html?mbox.msc?mbox=' +
    encode(rname) + '&start=' + (ind ? ind : 0) + '&count=' + main.cfg['meViewSize'] + 
    '&date=true&sortorder=' + main.sortOrder + '&sortby=' + main.sortBy + 
    '&headerv=Content-type&sid=' + main.sid + '&lang=' + main.lang

  if (rname == main.cfg['meSentFolder'] || rname == main.cfg['meDraftFolder'])
    s += '&hdr=to' 

  s += '&srch='

  if (srch && (srch.indexOf('deleted')>-1 || srch.indexOf('ALL')> -1))
    s += encode(srch)
  else if (srch)
    s += encode(srch + ' NOT deleted')
  else
    s += encode('ALL NOT deleted')

  return s
}

function msgURL(idx) {
  var msg = mboxFrame.msg[idx]
  var binhex, maxtext, newstr
  binhex = main.mac ? '' : ',binhex'
  maxtext = '&maxtext=55000'
  var uid = msg.uid
  
  if (msg.flags & mboxFrame.flag['\\seen'])
     newstr = '&newmsg=0'
  else
     newstr = '&newmsg=1'

  var s = 'mbox=' + encode(mboxFrame.mbox) + '&uid=' + uid + '&msgid=' + idx + 
    '&start=' + mboxFrame.start + '&count=' + mboxFrame.count +
    '&process=js,link,target,html' + binhex + maxtext + '&sid=' + main.sid + '&lang=' + main.lang + newstr

  if (msg.flags & main.mboxFrame.flag['\\draft'])
    return 'javascript: main.compose(\'draft\', \'' + main.msgHREF + 'msg.msc?' + s + '\')'
  else
    return  main.msgHREF + 'history.html?msg.msc?' + s
}

function SpecialMboxURL(sname) {
  var key = 'me' + sname + 'Folder'
  if (sname == 'Drafts') key = 'meDraftFolder'
  var mboxname = main.cfg[key] ? main.cfg[key] : sname
  var start = 0
  var srch = ''
  if (main.state=='msg' && mboxname == msgFrame.mbox) {
    start = mboxFrame.start
    srch = mboxFrame.srch
  }
  return MboxURL(mboxname, start, srch)
}

function folderTab() {
  return ''
}

function flagimg(msg) {

  var msgstate = 0
  var s = ''

  if(msg.flags & main.mboxFrame.flag['\\deleted'])
    msgstate = msgstate | 1

  if(msg.flags & main.mboxFrame.flag['\\answered'])
    msgstate = msgstate | 2

  if(msg.flags & main.mboxFrame.flag['\\seen'])
    msgstate = msgstate | 4

  if(msg.flags & main.mboxFrame.flag['\\flagged'])
    msgstate = 8
  s += '<img src='

  switch(msgstate) {
    case 0 :
      s += 'imx/LrlUnrdMsg_1.gif' + ' alt="' + i18n['msg UnRead'] + '" '
      break
    case 1 :
      s += 'imx/LrlUnrdDelMsg_1.gif' + ' alt="' + i18n['msg UnreadDel'] + '" '
      break
    case 4 :
      s += 'imx/LrlRdMsg_1.gif' + ' alt="' + i18n['msg Read'] + '" '
      break
    case 5 :
      s += 'imx/LrlRdDelMsg_1.gif' + ' alt="' + i18n['msg ReadDel'] + '" '
      break
    case 6 :
      s += 'imx/LrlRdAnsMsg_1.gif' + ' alt="' + i18n['msg ReadAns'] + '" ' 
      break
    case 7:
      s += 'imx/LrlRdAnsDelMsg_1.gif' + ' alt="' + i18n['msg ReadAnsDel'] + '" '
      break
    case 8:
      s += 'imx/flagged.gif' + ' alt="' + i18n['mbox flagged'] + '" '
      break
    }
  return s
}

function findParent(i, mbox){
  var t = mbox[i].name.lastIndexOf("/")
  if (t==-1)
    return 0
  
  var p = mbox[i].name.substring(0, t)
  for (t=i-1; t>0 ; t--) {
    if (mbox[t].name==p)  return t+1
  }
  return 0
}

function getLocalizedName(fldr) {
    if(fldr == 'INBOX')
      return main.fldr['INBOX'];
    else if(fldr == main.cfg['meTrashFolder'])
      return main.fldr['Trash'];
    else if(fldr == main.cfg['meSentFolder'])
      return main.fldr['Sent'];
    else if(fldr == main.cfg['meDraftFolder'])
      return main.fldr['Drafts'];
    else return fldr;
}

var mbox = new Array()

function findIdx(n) {
  for (t=0; t<mbox.length; t++) {
    if (mbox[t].name == n)
    return t+1
  }
 return 1
}

function updateTreeCt(mbox){
  var M = main.cfgFramembox(mbox), s, t
  var idx = findIdx(mbox)
  var img = document.getElementById('iDTREE' + idx)
  var lnk = document.getElementById('sDTREE' + idx)
  s = split(mbox, '/')
  mbox = html(getLocalizedName(s[s.length - 1]))
  t = mbox + ': ' + M.msgs + ' ' + i18n['fldr messages']
  if (!isNaN(M.unread)) {
    s = '<b>' + mbox + ' ('+ M.unread + ')</b>'
    t += ', ' + M.unread + ' ' + i18n['msg UnRead']
  }
  lnk.innerHTML = s
  img.title = img.alt = lnk.title = t
}

function folderTree() {
  var folderlink = ' '
  var icon, unread=''
  var mb = main.cfgFrame.mbox
  var sb = main.cfgFrame.sub
  DTREE = new dTree('DTREE')  // Don't add var here!!

  if(main.cfg['mail'] != null)
  for (i=0; i<mb.length; i++) {
    mbox[i] = mb[i]
  }
  for (i=0; i<sb.length; i++) {
    mbox[i+mb.length] = sb[i]
  }

  if(main.cfg['mail'] != null)
    DTREE.add(0,-1, main.cfg['mail'], "history.html?fldr_fs.html", main.cfg['mail'])
  else
    DTREE.add(0,-1, i18n['manage folders'], "history.html?fldr_fs.html", i18n['manage folders'])
 
  for (i = 0; i < mbox.length; i++) {
  	temp = split(mbox[i].name, '/')
    folderlink = ''
    if (!(mbox[i].flags & main.cfgFrame.flag['\\noselect']))
      folderlink = MboxURL(mbox[i].name) + '" target="historyFrame" )"' +
        ' onMouseOut="return hint()" class=Lnk'
    icon = 'folder-closed.jpg'
    if (mbox[i].name == main.cfg['meDraftFolder'])
      icon = 'folder-Drafts.jpg'
    else if (mbox[i].name == main.cfg['meSentFolder'])
      icon = 'folder-Sent.jpg'
    else if (mbox[i].name == main.cfg['meTrashFolder'])
      icon = 'folder-Trash.jpg'
    else if (mbox[i].name == 'INBOX')
      icon = 'folder-INBOX.jpg'

    var ff = fldr_name = html(getLocalizedName(temp[temp.length - 1]))

    var tooltip = fldr_name + ': ' + mbox[i].msgs + ' ' + i18n['fldr messages']
    if (mbox[i].unread) {
      ff = '<b>' + fldr_name + ' (' + mbox[i].unread + ')' + '</b>'
      tooltip += ', ' + mbox[i].unread + ' ' + i18n['msg UnRead']
    }
    DTREE.add(i+1, findParent(i, mbox), ff, folderlink, tooltip, '',
        'imx/'+icon)
  }

  DTREE.add(mbox.length + 1, 0, i18n['manage folders'], "history.html?fldr_fs.html", i18n['manage folders'], 'mailFrame', 'imx/manage.png')

  return DTREE
}

function quotaBar() {
  var qsize = parseInt(main.cfg['mailQuota'])
  if (qsize < 0) return ' '
  var pc =  Math.round((mboxFrame.mailQuotaUsed/qsize*100))
  if(pc == null || main.cfg['mailQuota'] == null)
    return ' '
  var color = 'green'
  if (pc > 60 )
    color = 'orange'
  if (pc > 90)
    color = 'red'
  var s = '<div id="MS_quota" style="width: 130px; border: 1px solid black; background-color: #FFF; margin: 5px; padding: 1px">' +
    '<span style="float: left; width: ' + (pc>100 ? 100 : pc) +
    '%; background-color: ' + color + ';"> &nbsp;</span>' +
    '<span style="width: 1%;"> &nbsp;</span></div>' +
    '<p style="padding:0px; margin: 0px; margin-bottom:10px"> &nbsp;' + i18n['quota'] + ' : ' + pc + '% ' + i18n['of'] + ' ' + size(main.cfg['mailQuota']) + '</p>'
  return s
}

function mailui_adjustHeight(objl, objm, objr) {
  objm = document.getElementById(objm)
  objl = document.getElementById(objl)
  objr = document.getElementById(objr)
  var max = Math.max(objl.scrollHeight, objr.scrollHeight)
  max = Math.max(max, document.body.clientHeight - 145)
        
  objm.style.height = max
}
