/* procedures that implement move and resize div actions

Useage:
  1) use create_moveBox to create a "moveable box". These are "absolute" DIVS, that you can
     drag to a new spot, or resize.
  2) Change the content of a moveable box using write_moveBox.
 
The moveable boxes can be:  
  * dragged to a different position in the browser window
  * resized
  * closed 
  * shrunk (a small "opener" box is dispalyed on screen)
  * can swap back and forth between displaying prior and current content
  * you can specify a popup menu, with specialized commands,

Functions:
  bnumber=create_moveBox(boxNumber,[left,top],[width,height],'header','optionList')
  write_moveBox(boxNumber,adesc,acontent,append)
  writeHeader_moveBox(boxNumber,content,iappend)
  writeContent_moveBox(boxNumber,content,iappend)
  stuff=read_moveBox(boxNumber,iheader)
  wascurrent=current_moveBox(boxNumber) 
  close_moveBox(boxNumber)
  closeMenu_moveBox(boxNumber)
  delete_moveBox(boxNumber)
  open_moveBox(boxNumber)
  priorContent_moveBox(boxNumber)
  lock_moveBox(boxNumber,howto);
  transparent_moveBox(boxNumber);
  top_moveBox(boxNumber);
  copyTo_moveBox(ifrom,ito,iappend)
  exists_moveBox(boxNumber)

Syntax:

bnumber=create_moveBox(boxNumber,[left,top],[width,height],'title','optionList')

 where:
    boxNumber: required: you can specify many different boxes, that will be identified by a number (0,1,2...)

               Alternative: if boxNumber not specified, of equals '', a number will be automatically assigned.
                            This number, returned in bnumber, can be used in write_moveBox, etc.

    [left,top]: the position (relative to top-left corner of browser window) of the top-left corner of the box.
                If not specified, or if '' is used, a default location is used
                This should be in pixels.

    [width,height] : width and height of the box (in pixels)

     Note:  left, top, width, and height can be specified as a % (of the window)
         For example ['10%','66%'] would be 2/3 down the window, 10% indented from the left

    title: optional. A short message displayed in the top border of the box
    optionList: optional. A list of options, in a space delimited string
        Allowed options. Defaults are used an option is not specified
           LOCK  - fixed position (does not move when screen is scrolled). 
           TRANS=aval  - Transparency. Aval is between 0.0 and 1.0 (0=not transparent). 
           BORDER=aColor - Border color. aColor should be a color (i.e.'RED') or a #rrggbb (ie;'#aaffcc'). 
           BOXSTYLE=cssStyle   - A  css style to apply to the message box. 
                          Example: BOXSTYLE=border:2px_solid_blue will put a blue frame around the entire box
                           (note: underscores are converted to spaces)
                          CAUTION: don't get too fancy -- you could end up messing up the styles used to display the
                                   moveable box.
           MENU=divId  - alternate menu (when upper-left-corner is clicked). divId should be the id of an existing element.
           MENU2=divId  - as above, but add a "close menu" and "close this box" buttons
                         Not: if no divId, then just put a close this box button
           MENUADD=divid -- add elements in divid to bottom of menu. Unlike, MENU and MENU2, the
                                    "default" menu is retained (with new stuff adde to the bottom)
                                 Note: menuadd is ignored if MENU or MENU2 is specified 
                                 Hint: use a <div  class="moveBoxMenuRow"> ... to match the style of the
                                       rows in the generic      menu

     Be sure to have a space between options, but NO spaces within (that is, no spaces before or after an '='
        
    bnumber: the box number created. If boxNumber not specified, this is the number to be used in write_moveBox
             and other functions.
        
 Note: if you create a box, using a box number used for a prior box, the old box will be deleted.


write_moveBox(boxNumber,adesc,acontent,append)

 where:
    boxNumber : required. Should correspond to a boxNumber used in a create_moveBox. If you use a boxNumber for
                a box that has not been created, an error occurs.
                If boxNumber='', use the current moveBox

    header:  String, or a ''. A header to display at the top of the box. The header area's size does NOT change
             when a box is resized.  If '', the header area is not displayed

    content: String. The content to display -- it will be resized when the box is resized.

    append: optional. If 1, then append content (and header) to prior content and header.
                      If not specified, the "prior contents" will NOT be updated.


 writeHeader_moveBox(whichBox,content,iappend)
 writeContent_moveBox(whichBox,content,iappend)
        As above, but just write (append or replace) to the header, or the content, of the box


stuff=read_moveBox(boxNumber)
    Read the contents and header  (the innerHTMLs) of the boxNumber move box.
    If boxNumber is not specified, or is '', read the contents of the current moveBox.
    If iheader not specified, or 0, read contents. If 1, read header
 
    returns a 4 element array:
        [header,content,priorHeader,priorContent]


close_moveBox(boxNumber) 
   Closes a boxNumber. But does not destroy content. So if you subsequently open_moveBox, the 
   contents displayed at the moment you closed it will be redisplayed (assuming you have not
   use write_moveBox or create_moveBox with that box number).
   Note: will also close a moveBox menu (associated with this moveBox)

   Shortcut: close_moveBox() (or close_moveBox('')) will close the current moveBox.


closeMenu_moveBox(boxNumber)
   Closes a menu for boxNumber.  This is useful when used with custom menu items, say as added
   with menuAdd.

   Shortcut: closeMenu_moveBox() (or closeMenu_moveBox('')) will close the menu of the current
               moveBox.

delete_moveBox(boxNumber)
   Deletes a boxNumber: close box AND destroy content. So if you subsequently open_moveBox, an error will occur
   (since the box no longer exists).
   If the current moveBox is delete, the current move box is set to -1.

   Note: will also close/delete a moveBox menu (associated with this moveBox)

   Shortcut: delete_moveBox() (or delete_moveBox('')) will delete the current moveBox.
                

open_moveBox(boxNumber)
   Re-opens a boxNumber. Prior content is not effected.

   Shortcut: open_moveBox() (or open_moveBox('')) will re-open the current box.

             The "current" box is the box that has been most recently clicked on: that has
             been most recently moved, resized, sent to the front, or had its menu opened.

             Note: calling open_moveBox will set the current box.

acurrent=current_moveBox(iwhich) 
   Set the "current" moveBox to be iwhich.
   If no argument, returns the current moveBox.
   If iwhich points to a non-existent box, returns -1 (and does NOT change current move Box
   Otherwise returns the prior current box. If there is NO current move box, returns -1.


priorContent_moveBox(boxNumber)
   Toggles between display of "prior" contents, and "recent" contents of the box.
   Loading content, using write_moveBox, will always convert the currently displayed contents
   to the "prior contents" (even if the currently displayed contents is the prior contents, not the
   recent contents).

   Shortcut: priorContent_moveBox() (or priorContent_moveBox('')) will swap contents of the current
               moveBoxbox.

lock_moveBox(boxNumber,how);
  Lock/unlick  move box.

  howto: 1 lock, 0 to unlock
  If howto is not specified, toggle between locked and unlocked. 

   Shortcut: lock_moveBox() (or lock_moveBox('')) will toggle the lock/unlock 
             of the current moveBox.

transparent_moveBox(boxNumber);
  Toggle  transparency (between transparent and non-transparent). 
  If a box was opened without transparency, a default value (0.33) is used for transparency.

   Shortcut: transparent_moveBox() (or transparent_moveBox('')) will toggle transparency of the 
               current moveBox.

top_moveBox(boxNumber);
  The boxNumber moveBox is moved to the front (it will lie on top of all other moveBoxes).

copyTo_moveBox(ifrom,ito,iappend)
  Copy the contents of box ifrom, or element with id of ifrom, to box ito.
  append: optional. If 1, then append content (and header) to prior content and header.
                    If not specified, the "prior contents" will NOT be updated.
  
exists_moveBox(boxNumber)
  Returns a 0 if the boxNumber box does not exist.
            1 if it does
            2 if it does, and is open

shrink_moveBox(boxNumber)
   Shrink the move box. The box is closed. Then a small box is opened that, when clicked, will reopen the
   box. This small box will have the box number in it, with a mouseover title containing the box title
   (as specified in create_moveBox).
        This small box is placed in an element with id="_moveBoxOpeners". If no such element exists, shrink
         will shrink the box size and make it's contents transparent.
    Note: a "o" is placed in the upper corner in the box that calls shrink_moveBox (also, a shrink box
          choice is placed in the default popup menu).

unshrink_moveBox(boxNumber)
    Reopens the boxNumber move box, and removes the "small box" created by a shrink_moveBox.


Examples:

one could swap views of both of these content/header

  create_moveBox(0,[100,200],[500,100],' this is a box') ;
  acontent='<div style="background-color:blue;height:100%">'+
                 ' This is the content <p> and more content ... '+
            '</div>';                                                                            

  write_moveBox(0,'The header ',acontent);
  write_moveBox(0,'The 2 header <br>line 2 ','This is the 2 content <p> and more 2 content ... ');



the box will be hidden?
  create_moveBox(1,'','','abc','border=yellow') ;
  write_moveBox(1,' ','other content2 ' );
  if (confirm("hide box")) close_moveBox(1);

Note: the "acontent" variable above shows how to change the background color of the content.


Note:  shrink box requires existence of an element with an id="_moveBoxOpeners" 

*/


// == globals used by moveable/editable boxes
var _priorMoveBoxInfo={};
_priorMoveBoxInfo['last']=-1;
_priorMoveBoxInfo['track']=[];
_priorMoveBoxInfo['shrunk']=[];

var iarf=0;
var _firstMouseX=-1,_firstMouseY=-1;        // used to compute relative moves
var _nowMouseX=-1,_nowMouseY=-1;          // used to suppress small moves
var _lastClickX=-1,_lastClickY=-1;        // moves are relative to this position at first click
var _lastClickW=-1,_lastClickH=-1;        // resizes aree relative to this size at first click

var _mbGetSpot2=0;
var _mbChangeSize2=0;
var  _mbMaxZIndex=10 ;
var _mbNowWhich=-1;


//=========
// Create a moveable-box 

function create_moveBox(whichBox,apos,asize,aheader,aoptions) {

var uu,i ;
var edgesA=['showMoveBoxBEA_','showMoveBoxTEA_'];
var edges=['showMoveBoxLEB_','showMoveBoxREB_','showMoveBoxBEB_','showMoveBoxTEB_'];
var corners=["showMoveBoxBRC_","showMoveBoxTLC_"];
var itop,ileft ;
var rdiv,rdivname,iz,abox ;
var ileft,itop,iwidth,iheight,tmp,isLocked,uux,isTrans,whichBox,boxStyle ;
var aopts,aopt1,aoptions,ia,ifoo,addMenu,altMenuC,altMenu,taoptions,taopt1,menuClass ;

isLocked=0; isTrans=0;bcolor='';altMenu='';altMenuC=0 ;boxStyle='';addMenu='';
whichBox=_mbStrip(whichBox);

if (whichBox==='') {            // find first non-used box number
 whichBox=_priorMoveBoxInfo['track'].length ;
 for (var i=0;i< _priorMoveBoxInfo['track'].length ; i++ ) {
    if (_priorMoveBoxInfo['track'][i]=='') {            // deleted box, use it 
        whichBox=i;
        break;
    }
 }
}

if (arguments.length<2 || apos=='') {
   apos=[100+whichBox*16,100+whichBox*16];
}
if (arguments.length<3 || asize=='') {  
  asize=[400,250]
}
if (arguments.length<4) aheader='';
aheader=_mbStrip(aheader);

if (arguments.length<5) aoptions='' ;


if (typeof(apos)!=='object' || typeof(apos.length)=='undefined' || apos.length<2) {
        alert('Error in create_moveBox: bad position: '+apos);
        return -1;
}
if (typeof(asize)!=='object' || typeof(asize.length)=='undefined' || asize.length<2) {
        alert('Error in create_moveBox: bad size: '+asize);
        return -1;
}


ileft=apos[0] ; itop=apos[1];
 if (isNaN(ileft) && ileft.indexOf('%')>-1) ileft=parseInt(ileft)*window.innerWidth/100 ;            // % (not px)
 if (isNaN(itop) && itop.indexOf('%')>-1) itop=parseInt(itop)*window.innerHeight/100 ;
  ileft=parseInt(ileft); itop=parseInt(itop);
//alert(window.innerWidth+',' +window.innerHeight+'apos=='+apos+' and '+ileft+','+itop);

iwidth=asize[0]; iheight=asize[1];
 if (isNaN(iwidth) && iwidth.indexOf('%')>-1) iwidth=parseInt(iwidth)*window.innerWidth/100 ;            // % (not px)
 if (isNaN(iheight) && iheight.indexOf('%')>-1) iheight=parseInt(iheight)*window.innerHeight/100 ;
 iwidth=parseInt(iwidth); iheight=parseInt(iheight);

if (isNaN(ileft) || isNaN(itop) || isNaN(iwidth) || isNaN(iheight) ) {
  alert('Error in create_moveBox: size or position is not a number: '+apos+' ; '+asize);
  return -1;
}

_priorMoveBoxInfo['last']=whichBox ;

// check options:     LOCK  TRANS=aval  BORDER=aColor  MENU=divId MENU2=divId MENUDADD=divid

aoptions=_mbStrip(aoptions);
//taoptions=aoptions.toUpperCase() ;
if (aoptions!=='') {                    // got some options
  aopts=aoptions.split(' ');
  for (var ia=0;ia<aopts.length;ia++) {
     aopt1=_mbStrip(aopts[ia]); taopt1=aopt1.toUpperCase() ;
     if (aopt1=='') continue ;
     if (taopt1.indexOf('LOCK')>-1) isLocked=1;
     if (taopt1.indexOf('TRANS=')>-1) {
        ifoo=_mbStrip(aopt1.substr(6));
        isTrans=_mbStrip(ifoo);
        continue ;
     }
     if (taopt1.indexOf('BORDER=')>-1) {
        ifoo=_mbStrip(aopt1.substr(7));
        bcolor=_mbStrip(ifoo);
     }  
     if (taopt1.indexOf('BOXSTYLE=')>-1) {
        ifoo=_mbStrip(aopt1.substr(9));
        boxStyle=_mbStrip(ifoo);
        boxStyle=boxStyle.replace(/_/g,' ');
     }

     if (taopt1.indexOf('MENU=')>-1) {
        ifoo=_mbStrip(aopt1.substr(5));
        altMenu=_mbStrip(ifoo);
     }
     if (taopt1.indexOf('MENU2=')>-1) {
        ifoo=_mbStrip(aopt1.substr(6));
        altMenu=_mbStrip(ifoo);
        altMenuC=1;
     }

     if (taopt1.indexOf('MENUADD=')>-1) {
        ifoo=_mbStrip(aopt1.substr(8));
        addMenu=_mbStrip(ifoo);
     }


  }   
 
}                               // end of options

menuClass='moveBoxOptions';
if (altMenu!=='') {             // read in altMenu
  rdiv=document.getElementById(altMenu);
  if (!rdiv) {
        alert('Error in create_moveBox: alternate menu element not found= '+altMenu);
        return -1;
  }
  altMenu=rdiv.innerHTML ;
  tmp=_mbGetAttributes(rdiv,'class','0');
  if (tmp!=='0') menuClass=_mbStrip(tmp) ;
}

if (addMenu!=='') {             // read in altMenu
  rdiv=document.getElementById(addMenu);
  if (!rdiv) {
        alert('Error in create_moveBox: add menu element not found= '+addMenu);
        return -1;
  }
  addMenu=rdiv.innerHTML ;
  tmp=_mbGetAttributes(rdiv,'class','0');
  if (tmp!=='0') menuClass=_mbStrip(tmp) ;
}


// if a moveable box with this number exists, delete it
rdivName='showMoveBox_'+whichBox ;
iid=document.getElementById(rdivName);
if (iid) {
   iid.parentNode.removeChild(iid);
  _priorMoveBoxInfo['track'][whichBox]='';
}

// now, build the moveable box (as a div)
rdiv=document.createElement('div');

rdiv.setAttribute('id',rdivName);
rdiv.setAttribute('class','moveBoxMain');

rdiv.setAttribute('boxNumber',whichBox); 

_mbMaxZIndex++ ;
rdiv.style.zIndex=_mbMaxZIndex ;  
 
if (isLocked==0)  {
   rdiv.setAttribute('style','position:absolute;height:20px;width:20px;top:'+itop+'px;left:'+ileft+'px;z-index:'+_mbMaxZIndex);
} else {
   rdiv.setAttribute('style','position:fixed;height:20px;width:20px;top:'+itop+'px;left:'+ileft+'px;z-index:'+_mbMaxZIndex);
}

// na,content, header, default transparency, current trans, swap transparency, current transparency state (0=no)
 _priorMoveBoxInfo[whichBox]=[0,'','',-1,0,0,0];           

if (boxStyle!=='') {
abox='<table id="showMoveBoxOTable_1"  boxStyle="'+boxStyle+'" style="'+boxStyle+'" frame="outer" cellpadding="0" cellspacing="0" >';
} else {
abox='<table  id="showMoveBoxOTable_1"  boxStyle="" cellpadding="0" cellspacing="0" >';
}

abox=abox+' '+
'  <tr>'+  
'     <td>'+                    // upper left corner
'        <div id="showMoveBoxTLC_1"   ' +
'             class="moveBoxCornerLT" corner="1" title="Lock and other options"  >isLocked</div>'+
'     </td>'+
'     <td  align="center" bcolor > '+                   // upper edge (with HANDLE and HEADER)
'        <div title="Click and drag to move box"  id="showMoveBoxTEB_1" class="moveBoxEdgeTop"  bcolor >'+
'               <span id="showMoveBoxTitle_1" class="moveBoxEdgeTopInnerText"> aheader </span>'+
'               <span id="showMoveBoxShrink_1"  title="Click to shrink this  box (box_1) " class="moveBoxCornerRT" style="float:right;margin-right:2px">o</span> '+
'        </div>'+
'     </td>'+
'     <td>  '+                                         // upper right corner (with CLOSE)
'        <div id="showMoveBoxTRC_1"  class="moveBoxCornerRT" corner="2" ' +
'             title="Close box"  >X</div>'+
'     </td>'+
'  </tr>';

abox=abox+' '+
'  <tr> '+
'     <td  class="moveBoxLREdge" bcolor >'+             // left edge
'           <div id="showMoveBoxLEB_1"  title="Click and drag to move box" class="moveBoxLREdgeInner" ></div>  '+
'     <td >'+
'           <div id="showMoveBoxHeader_1" class="moveBoxHeader"  >  </div>'+                     // center
'           <div id="showMoveBoxContent_1" class="moveBoxContent"  style="width:iwidthpx;height:iheightpx">  </div>'+
'        </div>'+
'     </td>'+
'      <td class="moveBoxLREdge"  bcolor >'+                    // right edge
'            <div id="showMoveBoxREB_1"  title="Click and drag to move box." class="moveBoxLREdgeInner"></div>  '+
'       </td>'+
'  </tr>';

abox=abox+' '+
'  <tr>'+
'     <td>'+
'        <div id="showMoveBoxBLC_1"    class="moveBoxCornerLB" corner="4" ' +           // bottom left corner
'            title="Click and drag to resize box"   >&lt;&gt;</div>  '+
'     </td>'+
'     <td  align="center" bcolor > '+                                   // bottom edge
'        <div idToFront="showMoveBox_1" id="showMoveBoxBEB_1" class="moveBoxEdgeBottom"  bcolor >'+
'               <div  bcolor id="showMoveBoxBTitle_1" class="moveBoxEdgeBottomInnerText"  > &nbsp; </div>'+
'        </div>'+
'     </td>'+
'     <td>   '+
'        <div id="showMoveBoxBRC_1"  class="moveBoxCornerRB" corner="3" '+              //bottom right corner
'             title="Click and drag to resize box"  >o</div>    '+
'     </td> '+
'  </tr> ' ;


//'        <div idToFront="showMoveBox_1" id="showMoveBoxBEB_1" class="moveBoxEdgeBottom"  bcolor >'+
//'           <div title="Click and drag to move box" id="showMoveBoxBEB_1" class="moveBoxEdgeBottomInner" ></div>  '+
//'        </div>'+

abox=abox+' '+
'</table> '+
'</div>  ';

abox=abox.replace(/_1/g,'_'+whichBox);
abox=abox.replace(/iwidth/g,iwidth);
abox=abox.replace(/iheight/g,iheight);
if (aheader=='') {
    abox=abox.replace(/aheader/g,'.      .');
} else {
    abox=abox.replace(/aheader/g,aheader);
}

if (isLocked==1) {
  abox=abox.replace(/isLocked/g,'L');
} else {
  abox=abox.replace(/isLocked/g,' ');
}

if (bcolor!=='') bcolor='style="background-color:'+bcolor+'" ';

abox=abox.replace(/bcolor/g,bcolor);

rdiv.innerHTML=abox;
document.body.appendChild(rdiv);

_priorMoveBoxInfo[whichBox][3]=isTrans;
_priorMoveBoxInfo[whichBox][5]=isTrans;                         // swap transparency
if (isTrans==0) {
     _priorMoveBoxInfo[whichBox][5]=0.33 ;         //use this if no default  transparency 
} else {
     _priorMoveBoxInfo[whichBox][6]=1 ;         // flag indicating currently in a transparent mode
}

_mbTransparent(whichBox,isTrans);

// the drag handles for all 4 edges
for (var i=0; i<4; i++) {
  uu=document.getElementById(edges[i]+whichBox);
  if (!uu) {
        alert('Error in create_moveBox: element not found: '+edges[i]+whichBox);
        return -1;
  }
  uu.onmousedown=_mbDoStartMove ;
}

/* ===
// the move to front edges
for (var i=0; i<2; i++) {
  uu=document.getElementById(edgesA[i]+whichBox);
  if (!uu) {
        alert('Error in create_moveBox: element not found: '+edgesA[i]+whichBox);
        return -1;
  }
  uu.onmousedown=_mbDoChangeZindex ;
}
**/

// the corners
 uu=document.getElementById("showMoveBoxBRC_"+whichBox);        // resize screen 
  if (!uu) {
        alert('Error in create_moveBox: element not found: '+"showMoveBoxBRC_"+whichBox);
        return -1;
  }
  uu.onmousedown=_mbDoStartResize ;

  uux=document.getElementById("showMoveBoxTLC_"+whichBox);       // options box
  if (!uu) {
        alert('Error in create_moveBox: element not found: '+"showMoveBoxTLC_"+whichBox);
        return -1;
  }
  uux.onclick=options_moveBox; 
  uux.setAttribute('boxNumber',whichBox);

 uu=document.getElementById("showMoveBoxBLC_"+whichBox);        // resize screen 
  if (!uu) {
        alert('Error in create_moveBox: element not found: '+"showMoveBoxBLC_"+whichBox);
        return -1;
  }
  uu.onmousedown=_mbDoStartResize ;


 uu=document.getElementById("showMoveBoxShrink_"+whichBox);        // shrihk screen 
  if (!uu) {
        alert('Error in create_moveBox: element not found: '+"showMoveBoxShrink_"+whichBox);
        return -1;
  }
  uu.setAttribute('onClick',"shrink_moveBox("+whichBox+")");

  tmp="showMoveBoxTRC_"+whichBox;                        // close box
  uu=document.getElementById(tmp);
  if (!uu) {
        alert('Error in create_moveBox: element not found: '+tmp);
        return -1;
  }
  uu.setAttribute('onClick',"close_moveBox("+whichBox+")");



// ==== options box

if (altMenu=='' && altMenuC!==1) {
  abox='<span>'+
'       <input class="moveBoxCloseMenu" type="button" value="m" id="showMoveBoxCLOSEMENU_1" '+
'               title="Close menu" /> '+
'       <input class="moveBoxMenuRowClose" type="button" value="S" id="showMoveBoxSHRINK_1" '+
'                title="Shrink this box" /> '+
'     <input class="moveBoxMenuRowClose" type="button" value="X" id="showMoveBoxCLOSE_1" '+
'                title="Close this box" /> '+
' </span>\n'+
'   <div class="moveBoxMenuRow"><input type="checkBox" value="551" id="showMoveBoxFIXED_1" lockChecked '+
'                title="Check this to lock the box (it will NOT move when content is scrollled)" > '+
'                <span id="showMoveBoxFIXEDB_1">Locked?</span> </div>\n'+
'   <div class="moveBoxMenuRow"><input type="checkBox" id="showMoveBoxTRANSPARENT_1" transChecked '+
'                title="Check this make box partially transparent" >'+
'                  <span  id="showMoveBoxTRANSPARENTB_1"> Transparent?</span> </div>\n'+  
'   <div class="moveBoxMenuRow"><input type="checkBox" id="showMoveBoxPRIORCONTENT_1" '+
'                title="Check this to display prior content" >'+
'                <span id="showMoveBoxPRIORCONTENTB_1">  Prior?</span> </div>\n'+
' ' ;

  if (addMenu!=='') {
     abox=abox+addMenu;
  }

} else {
 abox=altMenu;
if (altMenuC==1) {
    if (abox!=='') {
     abox='\n <span>'+
     '       <input class="moveBoxCloseMenu" type="button" value="x" id="showMoveBoxCLOSEMENU_1" title="Close menu" />  '+
     ' </span>\n'+ abox;
    }
    abox=abox+' ' +
     '   <div><input class="moveBoxMenuRowClose" type="button" value="close box" id="showMoveBoxCLOSE_1" '+
     '                title="Close this box" /> </div> ';
 }

}

abox=abox.replace(/_1/g,'_'+whichBox);
if (isTrans>0) {
  abox=abox.replace(/transChecked/g,'checked="1" ' );
} else {
  abox=abox.replace(/transChecked/g,' ' );
}

if (isLocked>0) {
  abox=abox.replace(/lockChecked/g,'checked="1" ' );
} else {
  abox=abox.replace(/lockChecked/g,' ' );
}

rdiv=document.createElement('div');
rdivName='showMoveBoxOptions_'+whichBox ;

iid=document.getElementById(rdivName);
if (iid) iid.parentNode.removeChild(iid);

rdiv.setAttribute('id',rdivName);
rdiv.setAttribute('boxNumber',whichBox);
rdiv.setAttribute('class',menuClass);
rdiv.setAttribute('style','display:none;position:absolute;top:322px;left:22px') ; 

rdiv.innerHTML=abox;
document.body.appendChild(rdiv);

  tmp="showMoveBoxFIXED_"+whichBox;                        // close box
  uu=document.getElementById(tmp);
  if (uu) uu.setAttribute('onClick',"options_moveBoxDo("+whichBox+",1)");   // 1: LOCK

  tmp="showMoveBoxFIXEDB_"+whichBox;                        // close box
  uu=document.getElementById(tmp);
  if (uu)  uu.setAttribute('onClick',"options_moveBoxDo("+whichBox+",11)");   // 11: LOCK

  tmp="showMoveBoxTRANSPARENT_"+whichBox;                      
  uu=document.getElementById(tmp);
  if (uu)   uu.setAttribute('onClick',"options_moveBoxDo("+whichBox+",2)");   // 2: TRANSPARENT

  tmp="showMoveBoxTRANSPARENTB_"+whichBox;                      
  uu=document.getElementById(tmp);
  if (uu)  uu.setAttribute('onClick',"options_moveBoxDo("+whichBox+",22)");   // 22: TRANSPARENT 

  tmp="showMoveBoxPRIORCONTENT_"+whichBox;                        
  uu=document.getElementById(tmp);
  if (uu)   uu.setAttribute('onClick',"options_moveBoxDo("+whichBox+",3)");   // 3: PRIORCONTENT

  tmp="showMoveBoxPRIORCONTENTB_"+whichBox;                        
  uu=document.getElementById(tmp);
  if (uu)  uu.setAttribute('onClick',"options_moveBoxDo("+whichBox+",33)");   // 33: PRIORCONTENT

  tmp="showMoveBoxSHRINK_"+whichBox;                        
  uu=document.getElementById(tmp);
  if (uu)   uu.setAttribute('onClick',"options_moveBoxDo("+whichBox+",6)");   // 6: shrink

  tmp="showMoveBoxCLOSE_"+whichBox;                        
  uu=document.getElementById(tmp);
  if (uu)  uu.setAttribute('onClick',"options_moveBoxDo("+whichBox+",4)");   // 4: close box

  tmp="showMoveBoxCLOSEMENU_"+whichBox;                        
  uu=document.getElementById(tmp);
  if (uu)   uu.setAttribute('onClick',"options_moveBoxDo("+whichBox+",5)");   // 5: close menu

  if (_mbStrip(aheader)=='') aheader='Box number '+whichBox;
 _priorMoveBoxInfo['track'][whichBox]=aheader;

 return whichBox ;

}


//==========================
// write  header of a moveable box
// writeHeader_moveBox(whichBox,content,iappend)
// iappend: 1= append  (else, replace)

function writeHeader_moveBox(iwhich,acontent,iappend) {
var iwhich,tname,iit,iframeE;

if (arguments.length<1 || _mbStrip(iwhich)=='') iwhich=_priorMoveBoxInfo['last']
iwhich=_mbStrip(iwhich) ;

if (isNaN(iwhich)|| iwhich==='' ) {
  alert('Error in writeHeader_moveBox: bad box number: '+iwhich);
  return 0;
}

if (arguments.length<3) iappend=0;

tname='showMoveBox_'+iwhich
iit=document.getElementById(tname);
if (!iit) {
  alert('Error in writeHeader_moveBox: no such box: '+iwhich);
  return 0;
}
    
iframeE=document.getElementById('showMoveBoxHeader_'+iwhich);
if (!iframeE) {
        alert('ERROR in writeHeader_moveBox-- can not find Header area of moveable box '+iwhich);
        return 1;
}

if (iappend==1) {
        iframeE.innerHTML=iframeE.innerHTML+acontent;
} else {
       _priorMoveBoxInfo[iwhich][2]=iframeE.innerHTML ;
       iframeE.innerHTML=acontent;
}

// suppress header area if empty string
if (_mbStrip(iframeE.innerHTML)=='') {
     iframeE.style.display='none';
   } else {
     iframeE.style.display='block';
  }


return 1;
}


//==========================
// write  content of a moveable box
// writeContent_moveBox(whichBox,content,iappend)
// iappend: 1= append adesc and acontent to both (else, replace)

function writeContent_moveBox(iwhich,acontent,iappend) {
var iwhich,tname,iit,iframeE;

if (arguments.length<1 || _mbStrip(iwhich)=='') iwhich=_priorMoveBoxInfo['last']
iwhich=_mbStrip(iwhich) ;

if (isNaN(iwhich)) {
  alert('Error in writeContent_moveBox: bad box number: '+iwhich);
  return 0;
}

if (arguments.length<3) iappend=0;

tname='showMoveBox_'+iwhich
iit=document.getElementById(tname);
if (!iit) {
   alert('Error in writeContent_moveBox: no such box: '+iwhich);
  return 0;
}
    
iframeE=document.getElementById('showMoveBoxContent_'+iwhich);
if (!iframeE) {
        alert('ERROR in n writeContent_moveBox-- can not find CONTENT area of moveable box '+iwhich);
        return 1;
}

if (iappend==1) {
        iframeE.innerHTML=iframeE.innerHTML+acontent;
} else {
       _priorMoveBoxInfo[iwhich][1]=iframeE.innerHTML ;
       iframeE.innerHTML=acontent;
}


return 1;
}




//==========================
// write header and content to a moveable box
// write_moveBox(whichBox,adesc,content)
// iappend: 1= append adesc and acontent to both (else, replace)

function write_moveBox(iwhich,aheader,acontent,iappend) {

if (arguments.length<1 || _mbStrip(iwhich)=='') iwhich=_priorMoveBoxInfo['last']
iwhich=_mbStrip(iwhich) ;

if (isNaN(iwhich)) {
  alert('Error in write_moveBox(: bad box number: '+iwhich);
  return 0;
}

if (arguments.length<4) iappend=0;

writeHeader_moveBox(iwhich,aheader,iappend);
writeContent_moveBox(iwhich,acontent,iappend);

return 1;

}

//=============== 

// move this moveBox to the front
function top_moveBox(iwhich) {
 var oof,ipp;
   oof='showMoveBox_'+iwhich ;
   ipp=document.getElementById(oof);

   _mbMaxZIndex++ ;
   if (ipp) ipp.style.zIndex=_mbMaxZIndex ;
return 0;
}

//===============
// toggle move box between locked and unlocked
function lock_moveBox(iwhich,howto) {
var iid,rdivName,islock,rdivNameTLC,iidTLC,csize,cpos;
var scrolls,aleft,atop ;
if (arguments.length<1 || _mbStrip(iwhich)=='') iwhich=_priorMoveBoxInfo['last']
if (arguments.length<2) howto=-1;
howto=strip(howto);

rdivName='showMoveBox_'+iwhich ;

iid=document.getElementById(rdivName);
if (!iid) {
  alert('Error in lock_moveBox: no such id= '+rdivName);
  return 0;
}

rdivNameTLC='showMoveBoxTLC_'+iwhich ;
iidTLC=document.getElementById(rdivNameTLC);
if (!iidTLC) {
  alert('Error in lock_moveBox: no such id= '+rdivName);
  return 0;
}

islock=iid.style.position;
aleft=parseInt(iid.style.left) ;atop=parseInt(iid.style.top);
scrolls=_mbGetScrollXY();

if (howto=='-1') {
  if (islock=='fixed') {
    iid.style.position='absolute';
    iidTLC.innerHTML=' ';
    iidTLC.setAttribute('title','Box is unlocked. Click to lock screen position');
    iid.style.left=(aleft+scrolls[0])+'px' ;                   // move to absolute location 
    iid.style.top=(atop+scrolls[1])+'px' ;
  } else {
     iid.style.position='fixed';
     iidTLC.innerHTML='L';
     iidTLC.setAttribute('title','Box is locked. Click to unlock screen position');
     iid.style.left=(aleft-scrolls[0])+'px' ;             
    iid.style.top=(atop-scrolls[1])+'px' ;
  }
} else {
  if (howto=='0') {
    iid.style.position='absolute';
    iidTLC.innerHTML=' ';
    iidTLC.setAttribute('title','Box is unlocked. Click to lock screen position');
    iid.style.left=(aleft+scrolls[0])+'px' ;                   // move to absolute location 
    iid.style.top=(atop+scrolls[1])+'px' ;
  } else {
     iid.style.position='fixed';
     iidTLC.innerHTML='L';
     iidTLC.setAttribute('title','Box is locked. Click to unlock screen position');
     iid.style.left=(aleft-scrolls[0])+'px' ;             
    iid.style.top=(atop-scrolls[1])+'px' ;
  }
}


return 1;

}

//===========
// toggle contents of a div
function priorContent_moveBox(ith) {
var adesc,acontent,ii,tmp;
var rdivname; 

if (arguments.length<1 || _mbStrip(ith)=='') ith=_priorMoveBoxInfo['last']

 rdivName='showMoveBoxContent_'+ith ;
 ii=document.getElementById(rdivName);
 tmp=ii.innerHTML ;
 ii.innerHTML= _priorMoveBoxInfo[ith][1];
  _priorMoveBoxInfo[ith][1]=tmp;

 rdivName='showMoveBoxHeader_'+ith;
 ii=document.getElementById(rdivName);
 tmp=ii.innerHTML ;
 ii.innerHTML= _priorMoveBoxInfo[ith][2];
  _priorMoveBoxInfo[ith][2]=tmp;


return 1 ;
}

 
// set the current movebox. If not argument, return value of "current" movebox
function current_moveBox(iwhich) {
var iwas ;
if (arguments.length>0) {
  iwas=_priorMoveBoxInfo['last'] ;  
  _priorMoveBoxInfo['last']=iwhich ;  
  return iwas;
} else {
  return  _priorMoveBoxInfo['last']
}
}


// return 1 if iwhich move box exists, 2 if exists and is open, 0 otherwise
function exists_moveBox(iwhich) {
var tname,iit ;
tname='showMoveBox_'+iwhich;
iit=document.getElementById(tname);
if (!iit) return 0;
if (iit.style.display!=='none') return 2;
return 1;
}


//================
// close a moveBox's menu
function closeMenu_moveBox(iwhich) {
var tname,iit,tname2;
if (arguments.length<1 || _mbStrip(iwhich)=='') iwhich=_priorMoveBoxInfo['last'] ;
tname='showMoveBox_'+iwhich

iit=document.getElementById(tname);
if (!iit) {
   alert('Error in closeMenu_moveBox: no such box: '+iwhich);
  return 0;
}

 tname2='showMoveBoxOptions_'+iwhich ;
 iit=document.getElementById(tname2);
 iit.style.display='none';
 return 0;
}


//================
// close a moveBox
function close_moveBox(iwhich) {
var tname,iit,tname2;
if (arguments.length<1 || _mbStrip(iwhich)=='') iwhich=_priorMoveBoxInfo['last'] ;
tname='showMoveBox_'+iwhich

iit=document.getElementById(tname);
if (!iit) {
   alert('Error in close_moveBox: no such box: '+iwhich);
  return 0;
}
iit.style.display='none';


 tname2='showMoveBoxOptions_'+iwhich ;
 iit=document.getElementById(tname2);
 iit.style.display='none';

return 0;
}


// shrink/unsrhink a moveBox
function shrink_moveBox(iwhich) {
var ii1,tname,aheader,inew,newbox,atitle=' ',ih,ii2,wash,wasw,waso,ii2a ;

ih=document.getElementById('showMoveBoxTitle_'+iwhich);
if (ih) atitle=ih.innerHTML;

ii1=document.getElementById("_moveBoxOpeners");

ii1=document.getElementById("_moveBoxOpeners");
if (!ii1) {

  ii2=document.getElementById('showMoveBoxContent_'+ith);
  if (ii2) {
    wash=getAttributes(ii2,'oldHeight','-1');
    if (wash=='-1') {                            // not shrunk, so shrink
       ii2.setAttribute('oldWidth',ii2.style.width);
       ii2.setAttribute('oldHeight',ii2.style.height);
       ii2.setAttribute('oldOpacity',ii2.style.opacity);

       ii2.style.width='30px'; 
       ii2.style.height='30px';  
       ii2.style.opacity=0.06;      

    } else {                                    // unshrink it
       wasw=getAttributes(ii2,'oldWidth','-1');
       waso=getAttributes(ii2,'oldOpacity','-1');
       ii2.style.width=wasw; 
       ii2.style.height=wash;
       ii2.style.opacity=waso; 

       ii2.setAttribute('oldWidth',-1);
       ii2.setAttribute('oldHeight',-1);
       ii2.setAttribute('oldOpacity',-1);

    }
    return 0 ;                            // no place to move to, just make the box small
  }
}

//iit=document.getElementById(tname);
//aheader=iit.innerHTML ;

close_moveBox(iwhich);

newbox='showMoveBoxOPENER_'+iwhich ;
inew=document.createElement('span');
inew.id=newbox;
inew.setAttribute('id',newbox);
inew.setAttribute('title','Click to expand box '+iwhich+'('+atitle+')' );
inew.setAttribute('onclick','unshrink_moveBox('+iwhich+')');
inew.style.fontStyle='oblique';
inew.style.margin="1px 5px 1px 5px ";
inew.style.padding="1px 5px 1px 2px ";   
inew.style.border='1px solid tan';
inew.style.float='left';
inew.innerHTML=iwhich;

ii1.appendChild(inew);
return 1 ;
}

function unshrink_moveBox(iwhich) {
var newbox,ii1;
if (exists_moveBox(iwhich)!==0) open_moveBox(iwhich);

newbox='showMoveBoxOPENER_'+iwhich ;
ii1=document.getElementById(newbox);
if (!ii1) return 0 ;                            // no shrunk node, give up
ii1.parentNode.removeChild(ii1);
return 1;
}

// delete a moveBox
function delete_moveBox(iwhich) {
var tname,iit,tname2;
if (arguments.length<1 || _mbStrip(iwhich)=='') iwhich=_priorMoveBoxInfo['last'] ;
tname='showMoveBox_'+iwhich

iit=document.getElementById(tname);
if (!iit) {
   alert('Error in delete_moveBox: no such box: '+iwhich);
  return 0;
}
iit.style.display='none';
iit.parentNode.removeChild(iit);

_priorMoveBoxInfo['track'][iwhich]='';

if (_priorMoveBoxInfo['last']==iwhich) _priorMoveBoxInfo['last']=-1 ;

tname2='showMoveBoxOptions_'+iwhich ;
iit=document.getElementById(tname2);
iit.style.display='none';
iit.parentNode.removeChild(iit);


return 0;
}


//========
// read contents of a move box. Returns in a 4 element array: 
// close a moveBox
function read_moveBox(iwhich) {
var tname,iit,tname2,tmp,acontent,aheader;
if (arguments.length<1 || _mbStrip(iwhich)=='') iwhich=_priorMoveBoxInfo['last'] ;
tname='showMoveBox_'+iwhich ;

iit=document.getElementById(tname);
if (!iit) {
   alert('Error in read_moveBox: no such box: '+iwhich);
  return '';
}

tname2='showMoveBoxHeader_'+iwhich;
iit=document.getElementById(tname2);
aheader=iit.innerHTML ;
tname2='showMoveBoxContent_'+iwhich;
iit=document.getElementById(tname2);
acontent=iit.innerHTML ;

// na,content, header, default transparency, current trans, swap transparency, current transparency state (0=no)


tmp=[aheader,acontent,_priorMoveBoxInfo[iwhich][2],_priorMoveBoxInfo[iwhich][1] ];
return tmp;

}

//========
// Read contents of a move box (just the header), and write to a movebox (content). Possibly append.
// if ito not specified, write to current movebox

function copyTo_moveBox(ifrom,ito,iappend) {
var tname,iit,tname2,stuff,ause;

if (arguments.length<2 || _mbStrip(ito)=='') ito=_priorMoveBoxInfo['last'] ;

if (arguments.length<3) iappend=0 ;

tname='showMoveBox_'+ito
iit=document.getElementById(tname);
if (!iit) {
   alert('Error in copyTo_moveBox: no such box to copy to: '+ito);
  return '';
}

if (!isNaN(ifrom)) {
  tname2='showMoveBox_'+ifrom;
  iit=document.getElementById(tname);
  if (!iit) {
     alert('Error in copyTo_moveBox: no such box to copy from: '+ifrom);
     return '';
  }
  ause=read_moveBox(ifrom);
  stuff=ause[1];
} else {
  iit=document.getElementById(ifrom);
  if (!iit) {
     alert('Error in copyTo_moveBox: no such element to copy from: '+ifrom);
     return '';
  }
  stuff=iit.innerHTML;
}

writeContent_moveBox(ito,stuff,iappend);
return 0;

}


// open a moveBox
function open_moveBox(iwhich) {
var tname,iit;
if (arguments.length<1 || _mbStrip(iwhich)=='') iwhich=_priorMoveBoxInfo['last']
tname='showMoveBox_'+iwhich
iit=document.getElementById(tname);
if (!iit) {
   alert('Error in open_moveBox: no such box: '+iwhich);
  return 0;
}
iit.style.display='block';

_priorMoveBoxInfo['last']=iwhich;

return 0;
}


// toggle transparency
function transparent_moveBox(ilit){
if (arguments.length<1 || _mbStrip(ilit)=='') ilit=_priorMoveBoxInfo['last']
_mbTransparentSwap(ilit) ;
return 0;
}


// =====================
// functions used by above (not meant to be called by programmers)
//==========================
// start process of moving a box
function _mbDoStartMove(e) {

  var ipp,ipp2,targ,foo,oof,iid,ii,ith;
  var bnum,m,aa,targ0;
  var mdiv,imdiv;

  if (!e) var e = window.event;
   if (e.target) targ = e.target;
   else if (e.srcElement) targ = e.srcElement;
   if (targ.nodeType == 3) targ = targ.parentNode;  // defeat Safari bug

   ith=_mbGetBoxNumber(targ);
   if (ith<0) return 0;
   _priorMoveBoxInfo['last']=ith

   oof='showMoveBox_'+ith ;
   ipp=document.getElementById(oof);

// if menu open, close it
   mdiv='showMoveBoxOptions_'+ith ;
   imdiv=document.getElementById(mdiv);
   if (imdiv) imdiv.style.display='none';


   _mbMaxZIndex++ ;
   ipp.style.zIndex=_mbMaxZIndex ;
 
   _mbGetSpot2=0; _mbChangeSize2=0;           // suppress any other active move/resize

   foo=_mbGetMouseXY(e) ;
   _firstMouseX=foo[0];_firstMouseY=foo[1] ;
   _nowMouseX=foo[0];_nowMouseY=foo[1] ;
   _mbGetSpot2=targ;              // the element that was clicked on

   iid=document.getElementById(oof);
   if (!iid) {
           alert('changeSize error: nothing to move: '+oof);
           return 0;
   }

   iid=document.getElementById(oof);
    _lastClickX=parseInt(iid.style.left) ;
    _lastClickY=parseInt(iid.style.top) ;

    if (iid.style.left.indexOf('%')>-1) {                    // % (not px)
          _lastClickX=parseInt(iid.style.left)*window.innerWidth ;
    }
    if (iid.style.top.indexOf('%')>-1) {
          _lastClickY=parseInt(iid.style.top)*window.innerHeight ;
    }

    document.onmouseup = _mbGetMouseXYatClick;       // on mouseUp, move ends!
    document.onmousemove = _mbGetMouseXYMove;       // on mousemove, move !

return 1;
}

//==========================
// start process of resizing a box 
function _mbDoStartResize(e) {
  var targ,foo,iid,oof;
  var bnum,m,aa,targ0;

  if (!e) var e = window.event;
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;
  if (targ.nodeType == 3) targ = targ.parentNode;  // defeat Safari bug

  _mbGetSpot2=0; _mbChangeSize2=0;           // suppress any other active move/resize

  foo=_mbGetMouseXY(e) ;
  _firstMouseX=foo[0];_firstMouseY=foo[1] ;
   _nowMouseX=foo[0];_nowMouseY=foo[1] ;

   _mbChangeSize2=targ;              // the element that was clicked on

   ith=_mbGetBoxNumber(targ);
  _priorMoveBoxInfo['last']=ith

   oof=_mbGetAttributes(_mbChangeSize2,'idToResize','showMoveBoxContent_'+ith);
   iid=document.getElementById(oof);
   if (!iid) {
           alert('changeSize error: no idToResize: '+oof);
           return 0;
   }

    _lastClickW=parseInt(iid.style.width) ;
    _lastClickH=parseInt(iid.style.height) ;
    if (iid.style.top.indexOf('%')>-1) {
          _lastClickW=parseInt(iid.style.width)*window.innerWidth ;
    }
    if (iid.style.height.indexOf('%')>-1) {                    // % (not px)
          _lastClickH=parseInt(iid.style.height)*window.innerHeight ;
    }

    document.onmouseup = _mbGetMouseXYatClick;       // on mouseUp, resize!
    document.onmousemove = _mbGetMouseXYMove;       // on mousemove, move !

}


//=================================
// make a moveable box transparent. afrac between 0 and 1 (1=transparent)
// if just one argumentc, use prior value. If no prior value, use 0.33 (and set prior to be 0.33)
// if afrac='swap', swap between prior and non-transparent 
// this assumes that arg [3] of _priorMoveInfo was set with the "default" transparency

function _mbTransparent(ilit,afrac,itmp){
var iopac,fopac,adiv,ii,vv ;

if (arguments.length<3) itmp=0 ;

adiv='showMoveBox_'+ilit ;
ii=document.getElementById(adiv);
if (!ii)  return 0;    // alert('Error in _mbFadeDiv: no such box= '+adiv);
                          
if (arguments.length<2) {                             // a "reset to current transparency" command
   if (typeof(_priorMoveBoxInfo[ilit][4])=='undefined') return 0 ;  // give up
   afrac=_priorMoveBoxInfo[ilit][4];
} 


fopac=1-parseFloat(afrac);
iopac=_mbStrip(parseInt(afrac*100));
ii.style.opacity=fopac;

/* ii.style.filter='alpha(opacity='+iopac+')';  (IE8 wont support setting transparency via javascript, so give up) */

if (itmp!==1) _priorMoveBoxInfo[ilit][4]=afrac;         // don't reset "current transparency" 


return 1;
}

// ==============
// toggle between no transparency and default transparency.
function _mbTransparentSwap(ilit){


adiv='showMoveBox_'+ilit ;
ii=document.getElementById(adiv);
if (!ii) return 0;

pstate=_priorMoveBoxInfo[ilit][6];
if (pstate==0) {                        // current state is not transparent
  _mbTransparent(ilit,_priorMoveBoxInfo[ilit][5]);
  _priorMoveBoxInfo[ilit][6]=1 ;
} else {
  _mbTransparent(ilit,0);
  _priorMoveBoxInfo[ilit][6]=0 ;
}
return 1;

}

// ==============
// == simple transparency
function _mbTransparentSimple(adiv,afrac){

var iopac,fopac,adiv,ii,vv;

iarf++;

ii=document.getElementById(adiv);
if (!ii) return 0; 
fopac=1-parseFloat(afrac);
iopac=_mbStrip(parseInt(afrac*100));

ii.style.opacity=fopac;
/* ii.style.filter='alpha(opacity='+iopac+')';  (IE8 wont support setting transparency via javascript, so give up) */


return 1;
}



//======
// extract a boxNumber (possibly from parent), or use _ith in id 
function _mbGetBoxNumber(targ) {
  var bnum,m,aa,targ0,ii;
   targ0=targ ;
   for (var m=0;m>-1;m++ ) {    
     aa=_mbGetAttributes(targ0,'boxNumber','-1');
     if (aa=='-1') {
        if (!targ0.parentNode) break ;
        targ0=targ0.parentNode ;   
     } else {
        return _mbStrip(aa);
     }
   }
   ii=targ.id.indexOf('_');
   ith=targ.id.substr(ii+1);
   if (isNaN(ith)) {
        alert('Error: unable to find boxNumber in '+targ.id);
        return -1 ;
   }
   return ith ;
}


//=================================
// resizes or moves box after a mouse move
function _mbGetMouseXYMove(e) {
 var mleft,mdown,oof,dx,dy;
 var ipp,ipp2,acorner;
 if (!e) var e = window.event;

 if (_mbGetSpot2==0  && _mbChangeSize2==0) {    // should never happen
    return 0;
}

 var foo=_mbGetMouseXY(e);
 if (Math.abs(foo[0]-_nowMouseX)<3 && Math.abs(foo[1]-_nowMouseY)<3) return 0 ; // small move, ignore

 _nowMouseX=foo[0]; _nowMouseY=foo[1] ;

 if (_mbGetSpot2!==0) {                    // a move !
    ith=_mbGetBoxNumber(_mbGetSpot2);
    oof='showMoveBox_'+ith;
    iid=document.getElementById(oof);
    dx=_nowMouseX-_firstMouseX ; dy=_nowMouseY-_firstMouseY ;        // else, move it by dx and dy where it was a click
    iid.style.left=(_lastClickX +dx)+'px' ;
    iid.style.top=(_lastClickY+dy)+'px' ;
    return 0 ;
}

 if (_mbChangeSize2!==0) {                    // a resize (16 dec 2010: only the 3 corner is enabled)
// corner: 1=up left, 2, up right, 3,bot right, 4 bot left 

   ith=_mbGetBoxNumber(_mbChangeSize2);
   oof=_mbGetAttributes(_mbChangeSize2,'idToResize','showMoveBoxContent_'+ith);
   dx=_nowMouseX-_firstMouseX ;  
   dy=_nowMouseY-_firstMouseY ;    

   iid=document.getElementById(oof);
     iid.style.width=(_lastClickW+dx)+'px' ;
     iid.style.height=(_lastClickH+dy)+'px' ;
}

/*===
     acorner=_mbGetAttributes(_mbChangeSize2,'corner','');
     if (acorner=='') {
          alert('Error in _mbgetMouseXYmove : no corner');
     }
     if (acorner=='1') {
          dx=_nowMouseX-_firstMouseX ;  
          dy=_nowMouseY-_firstMouseY ;    dy=-dy ;
       }
       if (acorner=='2') {
          dx=_nowMouseX-_firstMouseX ;  
          dy=_nowMouseY-_firstMouseY ;   dy=-dy ;
       }
       if (acorner=='3') {
          dx=_nowMouseX-_firstMouseX ;  
          dy=_nowMouseY-_firstMouseY ;    
       }
       if (acorner=='4') {
          dx=_nowMouseX-_firstMouseX ;  
          dy=_nowMouseY-_firstMouseY ;    
       }
      iid.style.width=(_lastClickW+dx)+'px' ;
      iid.style.height=(_lastClickH+dy)+'px' ;
=== */



return 0;
}



//==========================
// bring to front
function _mbDoChangeZindex(e) {
  var ipp,ipp2,targ,foo;
  if (!e) var e = window.event;
   if (e.target) targ = e.target;
   else if (e.srcElement) targ = e.srcElement;
   if (targ.nodeType == 3) targ = targ.parentNode;  // defeat Safari bug

   ipp=_mbGetAttributes(targ,'idToFront','');

   if (ipp!=='') {
        ipp2=document.getElementById(ipp);
        if (ipp2) {
           _mbMaxZIndex++ ;
           ipp2.style.zIndex=_mbMaxZIndex ;
        }
    }
   return 1;
}




//===============
// do an option checked in an the options box
// iopt: 1=lock (fixed), 2=transparent, 3=priorcontent, 4=close
function options_moveBoxDo(iwhich,iopt){
var tname,iit,tname2;
var tmp2,iit2;

tname='showMoveBox_'+iwhich
iit=document.getElementById(tname);
if (!iit) {
   alert('Error in options_moveBoxDo: no such box: '+iwhich);
  return 0;
}

tname2='showMoveBoxOptions_'+iwhich ;
iit=document.getElementById(tname2);

if (iopt==5) {                  // close menu
  tname2='showMoveBoxOptions_'+iwhich ;
  iit=document.getElementById(tname2);
  iit.style.display='none';
  return 0;
}

if (iopt==4) {                  // close move box
  tname2='showMoveBoxOptions_'+iwhich ;
  iit=document.getElementById(tname2);
  iit.style.display='none';
  close_moveBox(iwhich);
 return 0;
}



if (iopt==6) {                  // close move box
  tname2='showMoveBoxOptions_'+iwhich ;
  iit=document.getElementById(tname2);
  iit.style.display='none';
  shrink_moveBox(iwhich);
 return 0;
}


if (iopt==1 || iopt==11) {                  // lock
   lock_moveBox(iwhich);
   if (iopt==11) {
        iit.style.display='none';
        tmp2='showMoveBoxFIXED_'+iwhich;   
        iit2=document.getElementById(tmp2);
        iit2.checked=!iit2.checked;
   }
   return 0;
}
if (iopt==2 || iopt==22) {                  // transparent
   _mbTransparentSwap(iwhich);
   if (iopt==22) {
        iit.style.display='none';
        tmp2='showMoveBoxTRANSPARENT_'+iwhich;   
        iit2=document.getElementById(tmp2);
        iit2.checked=!iit2.checked;
   }
   return 0;
}

if (iopt==3 || iopt==33) {                  // prior
   priorContent_moveBox(iwhich);
   if (iopt==33) {
        iit.style.display='none';
        tmp2='showMoveBoxPRIORCONTENT_'+iwhich;   
        iit2=document.getElementById(tmp2);
        iit2.checked=!iit2.checked;
   }
   return 0;
}


}

//===============
// display the options box
function options_moveBox(e){
var targ,iie,tempX,tempY,iWhich,rdivName,iid,csize;

if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) targ = targ.parentNode;  // defeat Safari bug

iwhich=_mbGetAttributes(targ,'boxNumber','0'); 
_priorMoveBoxInfo['last']=iwhich ;

rdivName='showMoveBoxOptions_'+iwhich ;
var iid;
iid=document.getElementById(rdivName);
if (!iid) {
  alert('Error in options_moveBox: no such id= '+rdivName);
  return 0;
}

if (iid.style.display!=='none' ) {               // already open? Then close!
  iid.style.display='none';
  return 0;
}


iie = document.all?true:false;
if (iie) { // grab the x-y pos.s if browser is IE
 tempX = event.clientX + document.body.scrollLeft;
 tempY = event.clientY + document.body.scrollTop;
}
else {  // grab the x-y pos.s if browser is NS
  tempX = e.pageX;
  tempY = e.pageY;
}  
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;} 

_mbTransparentSimple(rdivName,0.04); 

iid.style.left=(3+tempX)+'px'; 
iid.style.top=(3+tempY)+'px';  
iid.style.display='block'
return 1;
}


//=======================================
//=================
// javascript io functions

// ================
// Strip leading and/or training spaces
// if which is L then leading only (left),
//             R, then trailing (right) only
// otherwise (if not specified), leading and traling
function _mbStrip(str,which) {
  if (typeof(str)=='number') {str=str+''; return str; }
  if (typeof(str)!='string') return str;
  if (arguments.length<2) {
      which=''
   } else {
    which=which.toUpperCase();
    which=which.replace(/\s+/g,'')
    which=which.substring(0,1);
  }
  if (which=='L')  return str.replace(/^\s+/, '');
  if (which=='R') return str.replace(/\s+$/, '');
  return str.replace(/^\s+|\s+$/g, '');                         // trim both sides

}


function _mbGetAttributes(anode,attlist,adefs) {

  var newobj,vlist,m2,anatt,annat_orig,anode,asString=0,mlen;
  var useall=0 ;
  if (arguments.length<2) attlist='*' ;
  if (attlist=='*') useall=1 ;
 
  if (arguments.length<3) { 
        newobj=new Object() ;
  } else {
      if (adefs===null || typeof(adefs)!='object') {            // perhaps a "return as string" signal?
             asString=1 ;
             newobj=new Object() ;
      } else {                         // is an object -- so use it
         newobj=adefs ;
      }
  }
   newobj['']='';                                 // used to store list of all attributes found
   if (useall==0) {                              // look for given set 
        vlist=attlist.split(' ');
        for (var m2=0; m2<vlist.length;m2++) {                        // initialize (set all attributes='', except predefined ones 
            anatt_orig=_mbStrip(vlist[m2]) ; anatt=anatt_orig.toUpperCase() ; 
            if (typeof(newobj[anatt])=='undefined') newobj[anatt]='' ; // note that newobj is also used to identify if a name is in attlist
        }
  }                                     // otherwise, get all attributes 

  try {
    var mlen=anode.attributes.length;
  }
  catch(err) {                          // possibly a comment  (anode.attributes.length doesnt exist)
    if (asString==1) return adefs ;                           // no attributes (matching attlist) found -- return default
    return newobj ;
   }
  for (var m2=0; m2<mlen;m2++) {                    
     anatt_orig=_mbStrip(anode.attributes[m2].name) ; anatt=anatt_orig.toUpperCase() ;
     if (useall==0) {                                           // only retain specified attriburtes
        if (typeof(newobj[anatt])=='undefined')  continue  ;               // don't care about this one, so skip it
     }
     if (asString==1) { 
        return anode.attributes[m2].value ;       // if asString, return first of the "attlist" attributes found (as a string)
     }
     newobj[anatt]=anode.attributes[m2].value ;
     newobj['0~'+anatt]=anatt_orig ;                  // original (case presreved) attribute name 
     newobj['']=newobj['']+anatt+' ';                        // if found, but not in list (and not *), just ignore 
  }

  if (asString==1) return adefs ;                           // no attributes (matching attlist) found -- return default 
  return newobj ;

}


//== for debugging 
function _mbWriteDoStatus(amess){
var ii=document.getElementById('cinfo');
ii.innerHTML=ii.innerHTML+'<p/>'+amess;
return 1;
}


//=======================================
//============
// javascript position, etc functions

//=================================
// on mouse up, end move or resize
function _mbGetMouseXYatClick(e) {
 var mleft,mdown,oof;
 var ipp,ipp2;

  if (!e) var e = window.event;
   if (e.target) targ = e.target;
   else if (e.srcElement) targ = e.srcElement;
   if (targ.nodeType == 3) targ = targ.parentNode;  // defeat Safari bug

   ii=targ.id.indexOf('_');
   ith=targ.id.substr(ii+1);
   _mbTransparent(ith);                                 // reset transparency

 _mbGetSpot2=0;                 // turn off move
  _mbChangeSize2=0 ;              // the element that was clicked on

 document.onmouseup = 0 ;
 document.onmousemove= 0 ;



return 0;
}


//=================================
// read current mouse position 
function _mbGetMouseXY(e) {
var tempX,tempY;

var iie = document.all?true:false;

if (iie) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
}
else {  // grab the x-y pos.s if browser is NS
tempX = e.pageX;
tempY = e.pageY;
}  
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;} 
return [tempX,tempY];
}

//========================================================= ss
// from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function _mbGetScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

/* Returns the client-window width and height in pixels
  From http://javascript.internet.com, created by: Konstantin Jagello | http://javascript-array.com
*/ 
function _mbWidthHeight() {
 var awidth,aheight;
 awidth= document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
 aheight=document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
 return [awidth,aheight] ;
}

/* from http://www.quirksmode.org/js/findpos.html */
function _mbFindPos(obj) {
 var curleft = curtop = 0;
 if (obj.offsetParent) {
      do {
	curleft += obj.offsetLeft;
	curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);
      return [curleft,curtop];
}
return [-1,-1] ;
}

