var isIE6CSS, isCSS, isW3C, isIE4, isNN4;
var throb = new Image(32,32);
var userPrefs;
throb.src = 'img/balls.gif';

var nothrob = new Image(32,32);
nothrob.src = 'img/balls-static.gif';

var queue = new Object();
    queue.priority = new Array();
    queue.commands = new Array();
    queue.status = 0;
    queue.lastQueueSize = 0;
    queue.attempts = 0;

function UI() {
   if (document.images) {
     isCSS = (document.body && document.body.style) ? true : false;
     isW3C = (isCSS && document.getElementById) ? true : false;
     isIE4 = (isCSS && document.all) ? true : false;
     isNN4 = (document.layers) ? true : false;
     isIE6CSS = (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) ? true : false;
   }
   this.height = getInsideWindowHeight();
   this.width = getInsideWindowWidth();
   this.x = this.width;
   this.y = this.height;
   this.dragging = '';
   this.items = new Array();
   this.subitems = new Array();
   this.headings = new Array();
   this.toolsbuilt = new Array();
   this.seen = new Object();
   this.state = new State();
   this.toolbarState = 1;
   this.menubarState = 1;
   this.keystate = new KeyState();
   var h = new Array('Icon','Subject','Spam','Sender','Date','msgSize','Flag');
   var hwidths = new Array(22, 0, 22, 150, 150, 50, 18);
   for (var i=0;i<h.length;i++) {
      this.headings[i] = { name: h[i], width: hwidths[i], visible: true };
   }
   this.toolbar = new Object();
}

function Zone(zone, top, left, height, width, border) {
//alert("Creating zone "+zone+": \ntop: "+top+"\nleft: "+left+" \nwidth: "+width+"\nheight: "+height);
   this.zone = zone;
   if (top    != '') this.top    = parseInt(top);
   if (left   != '') this.left   = parseInt(left);
   if (height != '') this.height = parseInt(height);
   if (width  != '') {
      this.width  = parseInt(width);
   } else {
      this.width = parseInt(document.getElementById(zone).width);
   }
   if (border != '') this.border = border;
}

Zone.prototype.render = function ( ) {
   var obj = document.getElementById(this.zone);
   
   if (obj) {
      if (this.top) { 
         if (typeof(this.top) == 'string') {
            obj.style.top = this.top;
         } else {
            obj.style.top = this.top + 'px';
         }
      } else { 
         this.top = getObjectTop(this.zone); 
      }
      try {
         if (this.left) { obj.style.left   = (typeof(this.left) == 'string') ? this.left : this.left   + 'px'; } else { this.left = getObjectLeft(this.zone); }
      } catch(e) { 
         errorHandler(e, 'object method RENDER - set left');
      }
      try {
         if (this.height) { 
            obj.style.height = (typeof(this.height) == 'string') ? this.height : this.height + 'px'; 
         } else if (this.zone) { 
            this.height = getObjectHeight(this.zone) + 'px'; 
         }
      } catch(e) { 
         // alert(this.zone+' '+this.height);
         errorHandler(e, 'object method RENDER - set height');
      }
      try {
         if (this.width) { obj.style.width  = (typeof(this.width) == 'string') ? this.width : this.width  + 'px'; } else { this.width = getObjectWidth(this.zone); }
      } catch(e) { 
         errorHandler(e, 'object method RENDER - set width');
      }
   }
}

function KeyState() {
   this.alt = '';
   this.shift = '';
   this.ctrl = '';
   this.meta = '';
}

function Obj() {
   this.name = '';
}

function State() {
   this.zone = '';
   this.msgID = '';
   this.lastMsgID = '';
   this.dragging = '';
   this.context = '';
   this.menu = '';
}

function gebi(obj) {
   return document.getElementById(obj);
}

function debug(obj, origin) {

   var dbg = '<form onsubmit="return false;"><input type="text" name="js" size="50" onchange="eval(this.value);"></form>';
try {
   dbg += ">>>>>> FROM: " + origin +"<hr>\n";
   for (var i in obj) {
      if (obj[i] != '') {
            dbg += i + ': ' + obj[i] + " ["+typeof(obj[i])+"]<br>\n";
/*
            if (typeof(obj[i]) == 'object') {
               dbg += "<blockquote>";
               for (var j in obj[i]) {
                  try {
                     var tmpobj = obj[i];
                     dbg = dbg + j + ': ' + tmpobj[j] + " ["+typeof(tmpobj[j])+"]<br>\n";
                  }
                  catch(e) { }
               }
               dbg += "</blockquote>";
            }
*/
            
        }
   }

   var debug = document.getElementById('debug');
   if (debug) {
      debug.innerHTML = debug.innerHTML + dbg;
      debug.style.backgroundColor = '#ffffaa';
      debug.style.position = 'absolute';
      debug.style.display = 'block';
      debug.style.right = '100px;';
      debug.style.bottom = '1px;';
      debug.style.width = '500px';
      debug.style.zIndex = '50000';
   }
}
catch(e) { }
}

// Generic errorHandler for all try/catch's throughout the application
// Pointing everything here for now with the intention of forwarding 
// all errors to server for logging and analysis
function errorHandler(err, caller) {
   var errstr = '';
   if (err) {
      for (var e in err) {
         errstr += e + ': ' + err[e] + "\n";
      }
   }
   alert("An error occured in "+caller+" with the following details:\n"+errstr);

   return true;
}

function getCookie(Name) {
   var search = Name + "="
   if (document.cookie.length > 0) { // if there are any cookies
      offset = document.cookie.indexOf(search) 
      if (offset != -1) { // if cookie exists 
    offset += search.length 
    // set index of beginning of value
    end = document.cookie.indexOf(";", offset) 
    // set index of end of cookie value
    if (end == -1) 
    end = document.cookie.length
    return unescape(document.cookie.substring(offset, end))
      } 
   }
}

function restoreWindow() {
   var ws = getCookie('ws');
   if (ws) {
      var lastwin = ws.split(/\:/);
      window.screenX = lastwin[0];
      window.screenY = lastwin[1];
      window.innerWidth = lastwin[2];
      window.innerHeight = lastwin[3];
   }
}

// Handle toolbar button press (fired by onmousedown event on toolbar button object)
function press(who) {
   if ((toolObj) && (toolObj[who])) {
      if (toolObj[who].disabled) {
         return true;
      }
   }
   var tl = document.getElementById(who);
      
   if (tl) {
      tl.style.top = '2px';
   }

   ui.state.pressing = 1;
   setTimeout("release('"+who+"')", 1000);
   return false;
}

// Handle toolbar button release (fired by onmouseup event on toolbar button object)
function release(who) {
   if (ui) {
      if (ui.state) {
         if (!ui.state.pressing) return true;   
      }
   }

   var el = document.getElementById(who);

   if (el) {
      el.style.top = '-1px';
   }
   ui.state.pressing = 0;
   return false;
}

// Make throbber image throb, setting fall-through 'stopThrob' at 25 seconds
// in case something goes wrong
function startThrob() {
   var ti = document.getElementById("throbber");
   if (ti) {
      if (ti.src != throb.src) {
         ti.src = throb.src;
      }
      
      enableBtn('actionstop');
      safeStop = setTimeout("stopThrob();", 25000);   // Safety net for stopping throbber if server never does - 25 seconds
   }
   return true;
}

// Stop throbber image from throbbing
function stopThrob() {
   var ti = document.getElementById("throbber");
   if (ti && (ti.src != nothrob.src)) {
      ti.src = nothrob.src;
   }   
   disableBtn('actionstop');
   return true;
}

function closeContext() {
   if (ui.state.contextOpen) {
      hide(ui.state.contextOpen);
      unmenuglow();

      ui.state.currentMenu = '';
      ui.state.contextOpen = '';
   }
}

function doContext(evt) {
   evt = evt ? evt : window.event;
   closeAll();
   
   ui.state.inContext = 0;
   ui.state.contextOpen = '';
   
   if ((ui.folder.match(/Contacts$/i)) && (ui.state.frameContext == 'messages')) {
      ui.state.contextOpen = 'contactMenu';
   } else {
      if (ui.state.frameContext == 'folders') {
         ui.state.contextFolder = ui.state.lastFolder;
         ui.state.contextOpen = 'folderMenu';
      } else if (ui.state.frameContext == 'messages') {
         ui.state.contextOpen = 'messageMenu';
      }
   }

   if (ui.state.contextOpen != '') {
      show(ui.state.contextOpen);
      shiftTo(ui.state.contextOpen, parseInt(evt.clientX), parseInt(evt.clientY));      
      setZIndex(ui.state.contextOpen, 999);
   }

   return false;
}

function menuglow(who, exe) {
   ui.state.currentMenu = who.id;

   if (who) {
      who = (who.nodeType == 1 || who.nodeType == 9) ? who : who.parentNode;
      who.style.backgroundColor = '#000099';
      who.style.color = '#ffffff';
   }
   ui.state.lastglow = who;
}

function unmenuglow(who) {
   if (!who) {
      who = ui.state.lastglow;
   }
   if (!ui.state.clicking) {
      ui.state.menu = '';
   }
   
   if (who) {
      who = (who.nodeType == 1 || who.nodeType == 9) ? who : who.parentNode;
      who.style.backgroundColor = '#d0d0d0';
      who.style.color = '#000000';
   }
}

function toolGlow(who, glow) {
   try {
      var id = who.id.replace(/Image/, '');
      if ((toolObj[id]) && (toolObj[id].disabled)) return false;
      who.style.backgroundColor = glow;
   } catch(e) {
      return errorHandler(e, 'toolGlow('+who+', '+glow+')');
   }
}

function toolDim(who) {
   try {
      who.style.backgroundColor = '#e0e0e0';
   } catch(e) {
      return errorHandler(e, 'toolDim('+who+')');
   }
}


var ui = new Obj();
function buildToolbar(obj, who) {
   if (ui.toolsbuilt) {
      if  (ui.toolsbuilt[obj[0].tool_container]) return true;
      ui.toolsbuilt[obj[0].tool_container] = 1;
   }
   var container = document.getElementById(obj[0].tool_container);
   
   if (!container) {
      alert("Could not get container for toolbar "+obj[0].tool_container);
   } else {   
      var curpos = 20;
      for (var item=1; item<obj.length; item++) {
         if (item != "0") {
            var doit = 0;
            if (userPrefs) {
               if ((userPrefs[0]) && (userPrefs[0].customtools) && (obj[item].toolclass!='btnsep') && (who != 'composer')) {
                  var ckey = 'toolbar_'+obj[item].toolid;
                  if (userPrefs[0][ckey]) { doit = 1; } else { doit = 0; }
               } else { doit = 1; }
            } else { doit = 1; }
            
            if (doit) {
               curpos = curpos + (parseInt(obj[item].width) + 5);
               
               var btnwrap = document.createElement("DIV");
               var xclass = (obj[item].disabled) ? ' inactive' : ' active';
            
               if (!obj[item].toolclass.match(/sep$/i)) {
                  btnwrap.setAttribute('onclick', obj[item].action);
                  btnwrap.setAttribute('id', obj[item].toolid);
                  btnwrap.setAttribute('class', obj[item].toolclass+'Wrap'+xclass);
               } else {
                  btnwrap.setAttribute('id', obj[item].toolid);
                  btnwrap.setAttribute('class', obj[item].toolclass);
               }

               if (document.all) {
                  btnwrap.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+obj[item].btnsrc+"', sizingMethod='scale')";
                  btnwrap.title = obj[item].alttxt;
               } else {
                  var btnimg = document.createElement("IMG");
                  btnimg.setAttribute('src', obj[item].btnsrc);
                  btnimg.setAttribute('height', obj[item].height);
                  btnimg.setAttribute('width', obj[item].width);
                  btnimg.setAttribute('border', '0');
                  btnimg.setAttribute('hspace', '0');
                  btnimg.setAttribute('vspace', '0');
                  btnimg.setAttribute('class', obj[item].toolclass);
                  btnimg.setAttribute('id', obj[item].toolid+'Image');
                  
                  if (obj[item].toolclass != 'btnsep') {
                     btnimg.setAttribute('onmouseover', "toolGlow(this, '"+obj[item].glowcolor+"');");
                     btnimg.setAttribute('onmouseout', 'toolDim(this); release("'+obj[item].toolid+'");');
                     btnimg.setAttribute('onmousedown', "toolGlow(this,'"+obj[item].activecolor+"'); press('"+obj[item].toolid+"')");
                     btnimg.setAttribute('onmouseup', "toolDim(this); release('"+obj[item].toolid+"')");
                  }
                  btnimg.setAttribute('style', 'z-index:999;');
                  btnimg.setAttribute('title', obj[item].alttxt);

                  btnwrap.appendChild(btnimg);
               }
               container.appendChild(btnwrap);
            }
         }
      }   
   }   
}

// Convert object name string or object reference
// into a valid element object reference
function getRawObject(obj) {
    var theObj;
    if (typeof obj == "string") {
       theObj = document.getElementById(obj);
    } else {
        // pass through object reference
        theObj = obj;
    }
    return theObj;
}

// Convert object name string or object reference
// into a valid style (or NN4 layer) reference
function getObject(obj) {
    var theObj = getRawObject(obj);
    return theObj;
}

// Position an object at a specific pixel coordinate
function shiftTo(obj, x, y) {
   var theObj = getObject(obj);
   if (theObj) {
      theObj.style.left = x + 'px';
      theObj.style.top = y + 'px';
   }
}

// Move an object by x and/or y pixels
function shiftBy(obj, deltaX, deltaY) {
   var theObj = getObject(obj);
   if (theObj) {
      // equalize incorrect numeric value type
      var units = (typeof theObj.left == "string") ? "px" : 0 
      theObj.style.left = getObjectLeft(obj) + deltaX + units;
      theObj.style.top = getObjectTop(obj) + deltaY + units;
   }
}

// Set the z-order of an object
function setZIndex(obj, zOrder) {
    var theObj = getObject(obj);
    if (theObj) {
        theObj.style.zIndex = zOrder;
    }
}

// Set the background color of an object
function setBGColor(obj, color) {
   var theObj = getObject(obj);
   if (theObj) {
      theObj.style.backgroundColor = color;
   }
}

// Set the visibility of an object to visible
function show(obj) {
    var theObj = getObject(obj);
    if (theObj) {
        theObj.style.display = "block";
        theObj.style.visibility = "visible";
    }
}

// Set the visibility of an object to hidden
function hide(obj) {
    var theObj = getObject(obj);
    if (theObj) {
        theObj.style.display = "none";
        theObj.style.visibility = "hidden";
    }
}

// Retrieve the x coordinate of a positionable object
function getObjectLeft(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (document.defaultView && document.defaultView.getComputedStyle) {
        var style = document.defaultView;
        var cssDecl = style.getComputedStyle(elem, "");
        result = cssDecl.getPropertyValue("left");
    } else if (elem.currentStyle) {
        result = elem.currentStyle.left;
    } else if (elem.style) {
        result = elem.style.left;
    } else if (isNN4) {
        result = elem.left;
    }
    return parseInt(result);
}

// Retrieve the y coordinate of a positionable object
function getObjectTop(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (document.defaultView && document.defaultView.getComputedStyle) {
        var style = document.defaultView;
        var cssDecl = style.getComputedStyle(elem, "");
        result = cssDecl.getPropertyValue("top");
    } else if (elem.currentStyle) {
        result = elem.currentStyle.top;
    } else if (elem.style) {
        result = elem.style.top;
    } else if (isNN4) {
        result = elem.top;
    }
    return parseInt(result);
}

// Retrieve the rendered width of an element
function getObjectWidth(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetWidth) {
        result = elem.offsetWidth;
    } else if (elem.clip && elem.clip.width) {
        result = elem.clip.width;
    } else if (elem.style && elem.style.pixelWidth) {
        result = elem.style.pixelWidth;
    }
    return parseInt(result);
}

// Retrieve the rendered height of an element
function getObjectHeight(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetHeight) {
        result = elem.offsetHeight;
    } else if (elem.clip && elem.clip.height) {
        result = elem.clip.height;
    } else if (elem.style && elem.style.pixelHeight) {
        result = elem.style.pixelHeight;
    }
    return parseInt(result);
}

// Return the available content width space in browser window
function getInsideWindowWidth() {
    if (window.innerWidth) {
        return window.innerWidth;
        // >>> Why doesn't this work right?!?
         // } else if (isIE6CSS) {
         // measure the html element's clientWidth
         // return document.body.parentElement.clientWidth
         if (document.body && document.body.parentElement && document.body.clientWidth) {
            return document.body.parentElement.clientWidth;
         } else if (document.body && document.body.clientWidth) {
            return document.body.clientWidth;
         }
    } else if (document.body && document.body.clientWidth) {
        return document.body.clientWidth;
    }
    return 0;
}

// Return the available content height space in browser window
function getInsideWindowHeight() {
    if (window.innerHeight) {
        return window.innerHeight;
    } else if (isIE6CSS) {
         // measure the html element's clientHeight
      //alert(document.body.parentElement.clientHeight);
         if (document.body && document.body.parentElement) {
            return document.body.parentElement.clientHeight;
         } else if (document.body && document.body.clientHeight) {
            return document.body.clientHeight;
         }
    } else if (document.body && document.body.clientHeight) {
        return document.body.clientHeight;
    }
    return 0;
}

function unhighlight(who,color,log,fldr) {
   /*
   var obj = document.getElementById(who);
   if ((obj) && (log == 'msg')) {
      var uhClass = (selection[who]) ? 'tbldata selRow' : 'tbldata msgRow';
      obj.setAttribute('class', uhClass);
   }
   */
}

function highlight(who, fldr, color, log) {
   //setStatus(fldr+' : '+who+' : '+log);
   if (ui) {
      if (ui.state) {
         if (log ==  'folder') {
            ui.state.overFolder = fldr;
            ui.state.lastFolder = fldr;
         }
         if ((log == 'msg') && (!ui.state.contextOpen)) ui.state.overmsgid = who;
      }
   }
   ui.over = who;
   /*
   var obj = document.getElementById(who);
   if ((obj) && (log == 'msg')) {
      var uhClass = (selection[who]) ? 'tbldata focusRow' : 'tbldata overRow';
      obj.setAttribute('class', uhClass);
   }
   */
}

function setContext(evt, who) {
   evt = (evt) ? evt : window.event;
   if (ui) {
      if (ui.state) {
         //setStatus('frameContext: '+who);
         ui.state.frameContext = who;
      }
   }
}

function setInnerHTML(who, what) {
   var obj = document.getElementById(who);
   if (obj) obj.innerHTML = what;
}

function showProgress(title, text, inc, pause) {
   startThrob();

   progressDialogState = 1;
   progressDialog = document.getElementById('progress');
   progressDialog.style.display = 'block';
   progressDialog.style.zIndex = 11000;
   
   setInnerHTML('progressHeader', title);
   setInnerHTML('progressStatus', text);
   
   doProgress(1, pause, inc);
}

var progressDialogBar;
function doProgress(barLen, pause, inc) {
   if (!inc) var inc = 1;
   if (!pause) var pause = 10;
   if (!progressDialogBar) progressDialogBar = top.document.getElementById("progressBar");

   if (progressDialogBar) {
      if (barLen > 395) barLen = 0;
      progressDialogBar.style.width = barLen + 'px';

      if (progressDialogState == 1) {
         setTimeout('doProgress( '+ (barLen + 1) +', '+pause+');', pause);
      }   
   }
}
var progressDialog;
function hideProgress() {
   progressDialogState = 0;
   stopThrob();
   if (!progressDialog) progressDialog = document.getElementById('progress');
   if (progressDialog) {
      progressDialog.style.display = 'none';
      progressDialog.style.display = 'none';
   }
}

function createCookie(name,value,days) {
   if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
   } else var expires = "";
   document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
   }
   return null;
}

function eraseCookie(name) {
   createCookie(name,"",-1);
}

function logout() {
   eraseCookie('pass');
   eraseCookie('secret');
   eraseCookie('k');
   
   self.close();
}

function blockEvent(evt) {
   evt = (evt) ? evt : event;
   evt.cancelBubble = true;
   if (!document.all) evt.stopPropagation();
   return false;
}

function doKeypress(evt) {
   evt = evt ? evt : ((event) ? event : null);
	if (evt) {
		var doit = '';
		var key = (!evt.keyCode) ? evt.charCode : evt.keyCode;
		var shifted = evt.shiftKey;
      
      setStatus('[keypress] '+key+((evt.ctrlKey)?' ctrl':'')+((evt.altKey)?' alt':'')+((evt.shiftKey)?' shift':'')+((evt.metaKey)?' meta':''));
      if (keyDefs[key]) {
         // Handle 'Enter' specially
         if ((key == 13) && (!ui.state.curmsgid)) return true;
         // KEY (no modifier keys)
         if (keyDefs[key].cmd) doit = keyDefs[key].cmd;
         // SHIFT-KEY
			if ((evt.shiftKey) && (keyDefs[key].shiftKey)) doit = keyDefs[key].shiftKey;
         // CTRL-KEY
			if ((evt.ctrlKey) && (keyDefs[key].ctrlKey)) doit = keyDefs[key].ctrlKey;
         // META-KEY
			if ((evt.metaKey) && (keyDefs[key].metaKey)) doit = keyDefs[key].metaKey;
         // SHIFT-META-KEY
			if ((evt.shiftKey) && (evt.metaKey) && (keyDefs[key].shiftmetaKey)) doit = keyDefs[key].shiftmetaKey;
         // SHIFT-CTRL-KEY
         if ((evt.shiftKey) && (evt.ctrlKey) && (keyDefs[key].shiftctrlKey)) doit = keyDefs[key].shiftctrlKey;
         // ALT-KEY
			if ((evt.altKey) && (keyDefs[key].altKey)) doit = keyDefs[key].altKey;
         // SHIFT-ALT-KEY
         if ((evt.shiftKey) && (evt.altKey) && (keyDefs[key].shiftaltKey)) doit = keyDefs[key].shiftaltKey;
			
			if (doit) {
            try {
               eval(doit);
            } catch(e) { 
               //errorHandler(e, 'doKeypress'); 
            }
            shifted = '';
            ui.state.shift = '';
            return blockEvent(evt);
			} 
		} 
	}
   shifted = '';
   ui.state.shift = '';
}

function doKey(evt) {
   evt = evt ? evt : ((event) ? event : null);
	if (evt) {
		var doit = '';
		var key = evt.keyCode;
		shifted = evt.shiftKey;
      setStatus('[keydown] '+key+((evt.ctrlKey)?' ctrl':'')+((evt.altKey)?' alt':'')+((evt.shiftKey)?' shift':''));

		if ((evt.keyCode == 18) && (activeButton)) {
         resetButton(activeButton);
         activeButton = null;
      }
      
      switch (evt.keyCode) {

         case 16 :
            ui.keystate.shift = true;
            break;
         case 17 :
            ui.keystate.ctrl = true;
            break;
         case 18 :
            ui.keystate.alt = true;
            break;
         case 19 :
            ui.keystate.meta = true;
            break;
      }
	}
   ui.state.shift = '';
   shifted = '';
   return blockEvent(evt);
}

function undoKey(evt) {
   evt = evt ? evt: ((event) ? event : null);
   shifted = '';
   if (evt) {
      switch (evt.keyCode) {

         case 16 :
            ui.keystate.shift = '';
            break;
         case 17 :
            ui.keystate.ctrl = '';
            break;
         case 18 :
            ui.keystate.alt = '';
            break;
         case 19 :
            ui.keystate.meta = '';
            break;
      }
   }
   ui.state.shift = '';
   shifted = '';
   return blockEvent(evt);
}

function closeAll() {
   var menus = new Array('file','edit','folders','messages','contacts','options','help');
   var dialogs = new Array('pwentry','folderDialog','progress','folderMenu','messageMenu','contactMenu');
   for (var m=0; m<menus.length; m++) {
      resetButton(menus[m]);
   }
   if (activeButton) resetButton(activeButton);
   if (ui.state.contextOpen) closeContext(ui.state.contextOpen);
   
   for (var m=0; m<dialogs.length; m++) {
      var el = document.getElementById(dialogs[m]);
      if (el) el.style.display = 'none';
   }
   //deselectall();
}

var dataTransport;
var tcount = 0;
function transport() {
   var mon = document.getElementById('showsel');
   if (mon) mon.innerHTML = "Transport #: "+tcount+"[priority: "+queue.priority.length+" command: "+queue.commands.length+"]<br>\n"+queue.priority.join("<br>\n")+"<br>\n"+queue.commands.join("<br>\n");

   if ((!queue.priority.length) && (!queue.commands.length)) {
      return false;
   }
   ++tcount;
   
  var cmd = '';
   if (queue.priority.length) {
      var pri = 1;
      cmd = queue.priority.shift();
   } else {
      var pri = 0;
      cmd = queue.commands.shift();
   }

   if ((cmd) && (queue.status==0)) {
      if (window.opener && (!pri)) {
         dataTransport = document.getElementById('transporter');
      } else {
         dataTransport = document.getElementById('priority');
      }

      if (dataTransport) {
         enableBtn('actionstop');
         queue.status = 1;
         ui.state.lastcmd = cmd;
         dataTransport.src = cmd;
      } else {
         if (pri) {
            queue.priority.unshift(cmd);
         } else {
            queue.commands.unshift(cmd);
         }   
      }
   }

     if ((queue.priority.length) || (queue.commands.length)) {
         ui.state.transporting = setTimeout('transport();', 1000);
      } else {
         ui.state.transporting = 0;
      }
}

function sendCmd(uri, priority, noui) {
   if (noui == 2) startThrob();
   
   //setStatus(uri+' Priority: '+priority);
   if (uri) {
      if (priority == 1) {
         queue.priority.push(uri);
      } else {
         queue.commands.push(uri);
      }
   }
 
   if (!ui.state.transporting) {
      setTimeout("transport();", 500);
   }
   
   return true;
}

var statusState = 0;
function toggleStatus() {
   var sta = document.getElementById('myfolder');
   if (!statusState) {
      statusState = 1;
      if (sta) sta.style.display = 'block';
   } else {
      statusState = 0;
      if (sta) sta.style.display = 'none';
   }
}

var selState = 0;
function toggleSel() {
   var sta = document.getElementById('showsel');
   if (!selState) {
      ui.state.showSel = 1;
      selState = 1;
      if (sta) sta.style.display = 'block';
   } else {
      ui.state.showSel = 0;
      selState = 0;
      if (sta) sta.style.display = 'none';
   }
}

function disableBtn(who) {
  if (typeof(who) == 'array') {
      for (var i in who) {
         var btn = document.getElementById(who[i]);
         if (btn) btn.className = 'button inactive';
      }
   } else {
      var btn = document.getElementById(who);
      if (btn) btn.className = 'button inactive';
   }

}

function enableBtn(who) {
   if (typeof(who) != 'string') {
      for (var i=0;i<who.length;i++) {
         var btn = document.getElementById(who[i]);
         if (btn) {
            toolObj[btn.id].disabled = 0;
            btn.className = 'button active';
         }
      }
   } else {
      toolObj[who].disabled = 0;
      var btn = document.getElementById(who);
      if (btn) btn.className = 'button active';
   }
}

function disableMsgUI() {
   var msgBtns = new Array('save','viewsource','print','reply','replyall','forward','trash','delete','spam');
   disableBtn(msgBtns);
}

function enableMsgUI() {
   var msgBtns = new Array('save','viewsource','print','reply','replyall','forward','trash','delete','spam');
   enableBtn(msgBtns);
}

function buildDropList(list, callback, x, y, w, h, sel) {
   var content = document.getElementById('content');
   var olddrop = document.getElementById('drop');
   if (olddrop) {
      var old = content.removeChild(olddrop);
   }
   var drop = document.createElement("DIV");
   drop.setAttribute('id', 'drop');
   drop.setAttribute('class', 'dropTop');

   var hgt = ((list.length * 20) > h) ? h : (list.length * 20);
   drop.setAttribute('style', 'top:'+y+'px;left:'+x+'px;width:'+w+'px;height:'+hgt+'px;');
   
   var shadows = new Array('RightTop','Right','Bottom','BottomLeft','Corner');
   var sdiv = new Array();

   for (var s=0;s<shadows.length;s++) {
      sdiv[s] = document.createElement('DIV');
      sdiv[s].setAttribute('id', 'shadow'+shadows[s]);
      sdiv[s].setAttribute('class', 'drop'+shadows[s]);
      sdiv[s].innerHTML = '&nbsp;';
      
      drop.appendChild(sdiv[s]);
   }

   //var txt = "<div id='dshadow'><img id='dshadowImg' height='"+(hgt + (hgt * .3))+"' width='"+((parseInt(w) + (parseInt(w) * .2)))+"' src='img/dropshadow.png'></div>";
   //txt += "<div onclick=\"document.getElementById('drop').style.display='none';\" id='dropClose'><a href='javascript:void(null);' onclick=\"document.getEle)mentById('drop').style.display='none';\"><img onclick=\"document.getElementById('drop').style.display='none';\" src='img/fileclose.png' border='0'></a></div>";
   //drop.innerHTML = txt;
   
   var dropMenu = document.createElement("DIV");
   dropMenu.setAttribute('id', 'dropMenu');
   
   var scrollStyle = '';
   if ((list.length * 20) > h) {
      scrollStyle = ' dropScroll';
   }
   dropMenu.setAttribute('class', 'dropFront'+scrollStyle);
   dropMenu.setAttribute('style', 'height:'+(hgt-12)+'px;width:'+(parseInt(w)-25)+'px;');
   var dropItem = new Array();
   
   for (var l in list) {
      dropItem[l] = document.createElement("DIV");
      dropItem[l].setAttribute('id', 'dl_'+l);

      if ((sel != null) && (l == sel)) {
         dropItem[l].setAttribute('class', 'dropList dropSelect');
      } else {
         dropItem[l].setAttribute('class', 'dropList');
      }
      
      dropItem[l].setAttribute('onmouseover', "lightDrop(event)");
      dropItem[l].setAttribute('onmouseout', "unlightDrop(event)");
      dropItem[l].setAttribute('onclick', callback+"(event, '"+l+"');");
      
      dropItem[l].innerHTML = list[l];
      
      dropMenu.appendChild(dropItem[l]);
   }

   drop.appendChild(dropMenu);
   
   content.appendChild(drop);
}

function lightDrop(evt) {
   evt = (evt) ? evt : window.event;

   var t = (evt.target) ? evt.target : evt.srcElement;
   t.style.backgroundColor = '#ccddff';
}

function unlightDrop(evt) {
   evt = (evt) ? evt : window.event;

   var t = (evt.target) ? evt.target : evt.srcElement;
   t.style.backgroundColor = 'transparent';
}

function selectFolder(node, who) {
   if ((node) && (!who)) var newdir = nodes[node];
   if (!node && !who) return false;

   if (newdir) {
      var parentDisp = document.getElementById('parentFolderDisplay');
      if (parentDisp) {
         parentDisp.innerHTML = newdir;
      }
   }
}

function newcontact() {

   contactwin = window.open("contact.php?d="+ui.folder+"&x=new","contactwin","toolbar=no,status=yes,location=no,directories=no,menubar=no,resizable=yes,scrollbars=yes,height=" + Math.round(ui.height * .80) + ",width=" + 575 +",dependent=no");

   if (contactwin) {
      contactwin.focus();
   } else {
      setTimeout('contactwin.focus();', 1000);
   }
   return false;
}

function openPrefs() {

   prefswin = window.open("prefs.php","prefswin","toolbar=no,status=no,location=no,directories=no,menubar=no,resizable=yes,scrollbars=no,height=500,width=800,dependent=no");

   if (prefswin) {
      prefswin.focus();
   } else {
      setTimeout('prefswin.focus();', 1000);
   }
   return false;
}

function openAccounts() {

   accountwin = window.open("accounts.php","accountwin","toolbar=no,status=no,location=no,directories=no,menubar=no,resizable=yes,scrollbars=no,height=400,width=800,dependent=no");

   if (accountwin) {
      accountwin.focus();
   } else {
      setTimeout('accountwin.focus();', 1000);
   }
   return false;
}


