eed2810ed6d1f108513493f532288fd9aac238a7
Merge parents db18564 bdb00f3
tdreszer
  Wed Oct 19 16:42:29 2011 -0700
Fix up a merge
diff --cc src/hg/js/hgTracks.js
index 6ba0bce,77fe196..04c39ac
--- src/hg/js/hgTracks.js
+++ src/hg/js/hgTracks.js
@@@ -1290,1793 -1432,1696 +1432,1696 @@@
                  var botdif = Math.abs(mapPortal.bottom - south);
                  if(topdif > 2 || botdif > 2) {
                      $(hDiv).height( mapPortal.bottom - mapPortal.top );
                      north = mapPortal.top * -1;
                      $(this).css( {'top': north.toString() + "px" });
  
                      // Need to adjust side label height as well!
                      var imgId = this.id.split("_");
                      var titlePx = 0;
                      var center = $("#img_center_"+imgId[2]);
                      if(center.length > 0) {
                          titlePx = $(center).parent().height();
                          north += titlePx;
                      }
                      var side = $("#img_side_"+imgId[2]);
-                     if( side.length > 0) {
+                     if (side.length > 0) {
                          $(side).parent().height( mapPortal.bottom - mapPortal.top + titlePx);
                          $(side).css( {'top': north.toString() + "px" });
                      }
                      var btn = $("#p_btn_"+imgId[2]);
-                     if( btn.length > 0) {
+                     if (btn.length > 0) {
                          $(btn).height( mapPortal.bottom - mapPortal.top + titlePx);
                      } else {
                          btn = $("#img_btn_"+imgId[2]);
-                         if( btn.length > 0) {
+                         if (btn.length > 0) {
                              $(btn).parent().height( mapPortal.bottom - mapPortal.top + titlePx);
                              $(btn).css( {'top': top.toString() + "px" });
                          }
                      }
                  }
              }
          });
          dragMaskResize();  // Resizes the dragMask to match current image size
      }
  
      function dragMaskShow() {   // Sets up the dragMask to show grabbing cursor within image and not allowed north and south of image
  
          var imgTbl = $('#imgTbl');
          // Find or create the waitMask (which masks the whole page)
-         var  dragMask = $('div#dragMask');
-         if( dragMask == undefined || dragMask.length == 0) {
+         var dragMask = $('div#dragMask');
+         if (dragMask == undefined || dragMask.length == 0) {
              $("body").prepend("<div id='dragMask' class='waitMask'></div>");
              dragMask = $('div#dragMask');
          }
  
          $('body').css('cursor','not-allowed');
          $(dragMask).css('cursor',"url(../images/grabbing.cur),w-resize");
-         $(dragMask).css({opacity:0.0,display:'block',top: $(imgTbl).position().top.toString() + 'px', height: $(imgTbl).height().toString() + 'px' });
+         $(dragMask).css({opacity:0.0,display:'block',
+                         top: $(imgTbl).position().top.toString() + 'px',
+                         height: $(imgTbl).height().toString() + 'px' });
          //$(dragMask).css({opacity:0.4,backgroundColor:'gray',zIndex:999}); // temporarily so I can see it
      }
  
      function dragMaskResize() {   // Resizes dragMask (called when image is dynamically resized in >1x scrolling)
  
          var imgTbl = $('#imgTbl');
          // Find or create the waitMask (which masks the whole page)
-         var  dragMask = $('div#dragMask');
-         if( dragMask != undefined && dragMask.length >= 1) {
+         var dragMask = $('div#dragMask');
+         if (dragMask != undefined && dragMask.length >= 1) {
              $(dragMask).height( $(imgTbl).height() );
          }
      }
  
      function dragMaskClear() {        // Clears the dragMask
          $('body').css('cursor','auto')
          var  dragMask = $('#dragMask');
-         if( dragMask != undefined )
+         if (dragMask != undefined )
              $(dragMask).hide();
      }
  
  
  
  };
  
- /////////////////////////////////////////////////////
- 
- function saveMouseOffset(ev)
- {   // Save the mouse offset associated with this event
-     originalMouseOffset = {x: ev.clientX, y: ev.clientY};
- }
- 
- function mouseHasMoved(ev)
- {   // return true if mouse has moved a significant amount
-     var minPixels = 10;
-     var movedX = ev.clientX - originalMouseOffset.x;
-     var movedY = ev.clientY - originalMouseOffset.y;
-     if ( arguments.length == 2) {
-         var num = Number(arguments[1]);
-         if(isNaN(num)) {
-             if ( arguments[1].toLowerCase() == "x" )
-                 return (movedX > minPixels || movedX < (minPixels * -1));
-             if ( arguments[1].toLowerCase() == "y" )
-                 return (movedY > minPixels || movedY < (minPixels * -1));
-         }
-         else
-             minPixels = num;
-     }
-     return (   movedX > minPixels || movedX < (minPixels * -1)
-             || movedY > minPixels || movedY < (minPixels * -1));
- }
- 
- function blockTheMap(e)
- {
-     blockUseMap=true;
- }
- 
- function blockTheMapOnMouseMove(ev)
- {
-     if (!blockUseMap && mouseHasMoved(ev)) {
-         blockUseMap=true;
-     }
- }
- 
- // wait for jStore to prepare the storage engine (this token reload code is experimental and currently dead).
- jQuery.jStore && jQuery.jStore.ready(function(engine) {
-     // alert(engine.jri);
-     // wait for the storage engine to be ready.
-     engine.ready(function(){
-         var engine = this;
-         var newToken = hgTracks.time;
-         if(newToken) {
-             var oldToken = engine.get("token");
-             if(oldToken && oldToken == newToken) {
-                 // user has hit the back button.
-                 jQuery('body').css('cursor', 'wait');
-                 window.location = "../cgi-bin/hgTracks?hgsid=" + getHgsid();
-             }
-         }
-         engine.set("token", newToken);
-     });
- });
- 
- function mapClk()
- {
-     return postToSaveSettings(this);
- }
- 
- function postToSaveSettings(obj)
- {
-     if(blockUseMap==true) {
-         return false;
-     }
-     if(obj == undefined || obj.href == undefined) // called directly with obj and from callback without obj
-         obj = this;
-     if( obj.href.match('#') || obj.target.length > 0) {
-         //alert("Matched # ["+obj.href+"] or has target:"+obj.target);
-         return true;
-     }
-     var thisForm=$(obj).parents('form');
-     if(thisForm == undefined || $(thisForm).length == 0)
-         thisForm=$("FORM");
-     if($(thisForm).length > 1 )
-         thisForm=$(thisForm)[0];
-     if(thisForm != undefined && $(thisForm).length == 1) {
-         //alert("posting form:"+$(thisForm).attr('name'));
-         return postTheForm($(thisForm).attr('name'),obj.href);
-     }
-     return true;
- }
- 
- function loadRemoteTracks()
- {
-     if(typeof(hgTracks.trackDb) != "undefined" && hgTracks.trackDb != null) {
-         for (var id in hgTracks.trackDb) {
+   ///////////////////////////////////////
+  //// rightClick (aka context menu) ////
+ ///////////////////////////////////////
+ var rightClick = {
+ 
+     menu: null,
+     selectedMenuItem: null,   // currently choosen context menu item (via context menu).
+     floatingMenuItem: null,
+     currentMapItem:   null,
+     supportZoomCodon: false,  // turn on experimental zoom-to-codon functionality (currently only on in larry's tree).
+ 
+     makeMapItem: function (id)
+     {   // Create a dummy mapItem on the fly (for objects that don't have corresponding entry in the map).
+         if(id && id.length > 0
+         && typeof(hgTracks.trackDb) != "undefined" && hgTracks.trackDb != null) {
+             var title;
              var rec = hgTracks.trackDb[id];
-             if(rec.type == "remote") {
-                 if($("#img_data_" + id).length > 0) {
-                     // load the remote track renderer via jsonp
-                     rec.loadingId = showLoadingImage("tr_" + id);
-                     var script = document.createElement('script');
-                     var pos = parsePosition(getPosition());
-                     var name = rec.remoteTrack || id;
-                     script.setAttribute('src', rec.url + "?track=" + name + "&jsonp=remoteTrackCallback&position=" +
-                                         encodeURIComponent(pos.chrom + ":" + pos.start + "-" + pos.end) +
-                                         "&pix=" + $('#imgTbl').width());
-                     document.getElementsByTagName('head')[0].appendChild(script);
-                 }
-             }
-         }
-     }
- }
- 
- $(document).ready(function()
- {
-     // The page may be reached via browser history (back button)
-     // If so, then this code should detect if the image has been changed via js/ajax
-     // and will reload the image if necessary.
-     // NOTE: this is needed for IE but other browsers can detect the dirty page much earlier
-     if (isDirtyPage()) {
-         // mark as non dirty to avoid infinite loop in chrome.
-         $('#dirty').val('false');
-         jQuery('body').css('cursor', 'wait');
-             window.location = "../cgi-bin/hgTracks?hgsid=" + getHgsid();
-             return false;
-     }
-     initVars();
-     var db = getDb();
-     if(jQuery.fn.autocomplete && $('input#suggest') && db) {
-         if(jQuery.fn.Watermark) {
-             $('#suggest').Watermark("gene");
-         }
-         $('input#suggest').autocomplete({
-             delay: 500,
-             minLength: 2,
-             source: ajaxGet(function () {return getDb();}, new Object),
-             open: function(event, ui) {
-                 var pos = $(this).offset().top + $(this).height();
-                 if (!isNaN(pos)) {
-                     var maxHeight = $(window).height() - pos - 30;  // take off a little more because IE needs it
-                     var auto = $('.ui-autocomplete');
-                     var curHeight = $(auto).children().length * 21;
-                     if (curHeight > maxHeight)
-                         $(auto).css({maxHeight: maxHeight+'px',overflow:'scroll'});
-                     else
-                         $(auto).css({maxHeight: 'none',overflow:'hidden'});
-                 }
-             },
-             select: function (event, ui) {
-                     setPosition(ui.item.id, commify(getSizeFromCoordinates(ui.item.id)));
-                     makeSureSuggestTrackIsVisible();
-                     // jQuery('body').css('cursor', 'wait');
-                     // document.TrackHeaderForm.submit();
-                 }
-         });
- 
-         // I want to set focus to the suggest element, but unforunately that prevents PgUp/PgDn from
-         // working, which is a major annoyance.
-         // $('input#suggest').focus();
-     }
- 
-     if(jQuery.jStore) {
-         // Experimental code to handle "user hits back button" problem by reloading the page based on the user's cart
-         if(jQuery.browser.msie && jQuery.browser.version < 8) {
-             // IE 7 requires flash to support jStore.
-             jQuery.extend(jQuery.jStore.defaults, {
-                               project: 'hgTracks',
-                               engine: 'flash',
-                               flash: '/jStore.Flash.html'
-                           });
-         }
-         jQuery.jStore.load();
-     }
- 
- 
-     // Convert map AREA gets to post the form, ensuring that cart variables are kept up to date (but turn this off for search form).
-     if($("FORM").length > 0 && $('#trackSearch').length == 0) {
-         var allLinks = $('a');
-         $( allLinks ).unbind('click');
-         $( allLinks ).click( postToSaveSettings );
-     }
-     if($('#pdfLink').length == 1) {
-         $('#pdfLink').click(function(i) {
-             var thisForm=$('#TrackForm');
-             if(thisForm != undefined && $(thisForm).length == 1) {
-                 //alert("posting form:"+$(thisForm).attr('name'));
-                 updateOrMakeNamedVariable($(thisForm),'hgt.psOutput','on');
-                 return postTheForm($(thisForm).attr('name'),this.href);
+             if(rec) {
+                 title = rec.shortLabel;
+             } else {
+                 title = id;
              }
-             return true;
-         });
-     }
-     if($('#imgTbl').length == 1) {
-         imageV2   = true;
-         initImgTblButtons();
-         // Make imgTbl allow draw reorder of imgTrack rows
-         var imgTable = $(".tableWithDragAndDrop");
-         if($(imgTable).length > 0) {
-             $(imgTable).tableDnD({
-                 onDragClass: "trDrag",
-                 dragHandle: "dragHandle",
-                 scrollAmount: 40,
-                 onDragStart: function(ev, table, row) {
-                     saveMouseOffset(ev);
-                     $(document).bind('mousemove',blockTheMapOnMouseMove);
- 
-                     // Can drag a contiguous set of rows if dragging blue button
-                     table.tableDnDConfig.dragObjects = [ row ]; // defaults to just the one
-                     var btn = $( row ).find('p.btnBlue');  // btnBlue means cursor over left button
-                     if (btn.length == 1) {
-                         table.tableDnDConfig.dragObjects = imgTblContiguousRowSet(row);
-                         var compositeSet = imgTblCompositeSet(row);
-                         if (compositeSet && compositeSet.length > 0)
-                             $( compositeSet ).find('p.btn').addClass('blueButtons');  // blue persists
-                     }
-                 },
-                 onDrop: function(table, row, dragStartIndex) {
-                     var compositeSet = imgTblCompositeSet(row);
-                     if (compositeSet && compositeSet.length > 0)
-                         $( compositeSet ).find('p.btn').removeClass('blueButtons');  // blue persists
-                     if($(row).attr('rowIndex') != dragStartIndex) {
-                         // NOTE Even if dragging a contiguous set of rows,
-                         // still only need to check the one under the cursor.
-                         if(imgTblSetOrder) {
-                             imgTblSetOrder(table);
-                         }
-                         imgTblZipButtons( table );
-                     }
-                     $(document).unbind('mousemove',blockTheMapOnMouseMove);
-                     setTimeout('blockUseMap=false;',50); // Necessary incase the onDrop was over a map item. onDrop takes precedence.
-                 }
-             });
-         }
-         if(hgTracks.imgBoxPortal) {
-             // Turn on drag scrolling.
-             $("div.scroller").panImages();
-         }
-         //$("#zoomSlider").slider({ min: -4, max: 3, step: 1 });//, handle: '.ui-slider-handle' });
- 
-         // Temporary warning while new imageV2 code is being worked through
-         if($('#map').children("AREA").length > 0) {
-             warn('Using imageV2, but old map is not empty!');
-         }
- 
-         // Retrieve tracks via AJAX that may take too long to draw initialliy (i.e. a remote bigWig)
-         var retrievables = $('#imgTbl').find("tr.mustRetrieve")
-         if($(retrievables).length > 0) {
-             $(retrievables).each( function (i) {
-                 var trackName = $(this).attr('id').substring(3);
-                 updateTrackImg(trackName,"","");
-             });
-         }
-         loadRemoteTracks();
-     }
-     if($('img#chrom').length == 1) {
-         if($('area.cytoBand').length > 1) {
-             $('img#chrom').chromDrag();
-         }
-     }
- 
-     if($("#tabs").length > 0) {
-         // Search page specific code
- 
-         var val = $('#currentTab').val();
-         $("#tabs").tabs({
-                             show: function(event, ui) {
-                                 $('#currentTab').val(ui.panel.id);
-                             },
-                             select: function(event, ui) { findTracksSwitchTabs(ui); }
-                         });
-         $('#tabs').show();
-         $("#tabs").tabs('option', 'selected', '#' + val);
-         if(val =='simpleTab' && $('div#found').length < 1) {
-             $('input#simpleSearch').focus();
-         }
-         $("#tabs").css('font-family', jQuery('body').css('font-family'));
-         $("#tabs").css('font-size', jQuery('body').css('font-size'));
-         $('.submitOnEnter').keydown(searchKeydown);
-         findTracksNormalize();
-         updateMetaDataHelpLinks(0);
-     }
- });
- 
- function rulerModeToggle (ele)
- {
-     autoHideSetting = !ele.checked;
-     var obj = imgAreaSelect.data('imgAreaSelect');
-     obj.setOptions({autoHide : autoHideSetting});
- }
- 
- function makeMapItem(id)
- {
-     // Create a dummy mapItem on the fly (for objects that don't have corresponding entry in the map).
-     if(id && id.length > 0
-     && typeof(hgTracks.trackDb) != "undefined" && hgTracks.trackDb != null) {
-         var title;
-         var rec = hgTracks.trackDb[id];
-         if(rec) {
-             title = rec.shortLabel;
+             return {id: id, title: "configure " + title};
          } else {
-             title = id;
+             return null;
          }
-         return {id: id, title: "configure " + title};
-     } else {
-         return null;
-     }
- }
+     },
  
- function mapItemMouseOver()
- {
-     // Record data for current map area item
-     currentMapItem = makeMapItem(this.id);
-     if(currentMapItem != null) {
-         currentMapItem.href = this.href;
-         currentMapItem.title = this.title;
-     }
- }
- 
- function mapItemMouseOut(obj)
- {
-     lastMapItem = currentMapItem;
-     currentMapItem = null;
- }
+     findMapItem: function (e)
+     {   // Find mapItem for given event; returns item object or null if none found.
  
- function findMapItem(e)
- {
- // Find mapItem for given event; returns item object or null if none found.
- 
-     if(currentMapItem) {
-         return currentMapItem;
-     }
+         if(rightClick.currentMapItem) {
+             return rightClick.currentMapItem;
+         }
  
-     // rightClick for non-map items that can be resolved to their parent tr and then trackName (e.g. items in gray bar)
-     if(e.target.tagName.toUpperCase() != "AREA") {
+         // rightClick for non-map items that can be resolved to their parent tr and then trackName (e.g. items in gray bar)
          var tr = $( e.target ).parents('tr.imgOrd');
-         if( $(tr).length == 1 ) {
+         if ( $(tr).length == 1 ) {
              var a = /tr_(.*)/.exec($(tr).attr('id'));  // voodoo
              if(a && a[1]) {
                  var id = a[1];
-                 return makeMapItem(id);
+                 return rightClick.makeMapItem(id);
              }
          }
-     }
+         warn("ASSERT: findMapItem failed.");// Should not ever get to this point
+         return null;
+     },
  
-     // FIXME: do we really need to worry about non-imageV2 ?
-     // Yeah, I think the rest of this is (hopefully) dead code
- 
-     var x,y;
-     if(imageV2) {
-         // It IS appropriate to use coordinates relative to the img WHEN we have a hit in the right-hand side, but NOT
-         // when we have a hit in the left hand elements (which do not have relative coordinates).
-         // XXXX still trying to figure this out.
-         var pos = $(e.target).position();
-         if(e.target.tagName == "IMG") {
-             // msie
-             // warn("img: x: " + x + ", y:" + y);
-             // warn("pageX: " + e.pageX + "; offsetLeft: " + pos.left);
-             x = e.pageX - pos.left;
-             y = e.pageY - pos.top;
-             // warn("x: " + x + "; y: " + y);
-         } else {
-             x = e.pageX - trackImg.attr("offsetLeft");
-             y = e.pageY - trackImg.attr("offsetTop");
-         }
-         // console.log(trackImg.attr("offsetLeft"), trackImg.attr("offsetTop"));
-         // console.log("findMapItem:", x, y);
-         // console.dir(mapItems);
-     } else {
-         x = e.pageX - e.target.offsetLeft;
-         y = e.pageY - e.target.offsetTop;
-     }
+     windowOpenFailedMsg: function ()
+     {
+         warn("Your web browser prevented us from opening a new window.\n\nPlease change your browser settings to allow pop-up windows from " + document.domain + ".");
+     },
  
-     var retval = -1;
-     // console.log(e.target.tagName + "; " + e.target.id);
-     for(var i=0;i<mapItems.length;i++)
+     handleZoomCodon: function (response, status)
      {
-         if(mapItems[i].obj && e.target === mapItems[i].obj) {
-             // e.target is AREA tag under FF and Safari;
-             // This never occurs under IE
-             // console.log("Found match by objects comparison");
-             retval = i;
-             break;
-         } else if (!imageV2 || browser == "msie") {
-             // Under IE, target is the IMG tag for the map's img and y is relative to the top of that,
-             // so we must use the target's src to make sure we are looking at the right map.
-             // We start falling through to here under safari under imageV2 once something has been modified
-             // (that's a bug I still haven't figured out how to fix).
-             if(mapItems[i].r.contains(x, y) && mapItems[i].src == $(e.target).attr('src')) {
-                 retval = i;
-                 break;
-             }
+         var json = eval("(" + response + ")");
+         if(json.pos) {
+             genomePos.set(json.pos, 3);
+             if(document.TrackForm)
+                 document.TrackForm.submit();
+             else
+                 document.TrackHeaderForm.submit();
+         } else {
+             alert(json.error);
          }
-     }
-     // showWarning(x + " " + y + " " + retval + " " + e.target.tagName + " " + $(e.target).attr('src'));
-     // console.log("findMapItem:", e.clientX, e.clientY, x, y, pos.left, pos.top, retval, mapItems.length, e.target.tagName);
-     // console.log(e.clientX, pos);
-     if(retval >= 0) {
-         return mapItems[retval];
-     } else {
-         return null;
-     }
- }
+     },
  
- function mapEvent(e)
- {
-     var o = findMapItem(e);
-     if(o) {
-         e.target.title = o.title;
-     } else {
-         // XXXX this doesn't work.
-         // $('#myMenu').html("<ul id='myMenu' class='contextMenu'><li class='edit'><a href='#img'>Get Image</a></li></ul>");
-         e.target.title = originalImgTitle;
-     }
- }
+     handleViewImg: function (response, status)
+     {   // handles view image response, which must get new image without imageV2 gimmickery
+         jQuery('body').css('cursor', '');
+         var str = "<IMG[^>]*SRC='([^']+)'";
+         var reg = new RegExp(str);
+         a = reg.exec(response);
+         if(a && a[1]) {
+             if(window.open(a[1]) == null) {
+                 rightClick.windowOpenFailedMsg();
+             }
+             return;
+         }
+         showWarning("Couldn't parse out img src");
+     },
+ 
+     myPrompt: function (msg, callback)
+     {   // replacement for prompt; avoids misleading/confusing security warnings which are caused by prompt in IE 7+
+         // callback is called if user presses "OK".
+         $("body").append("<div id = 'myPrompt'><div id='dialog' title='Basic dialog'><form>" +
+                             msg + "<input id='myPromptText' value=''></form>");
+         $("#myPrompt").dialog({
+                                 modal: true,
+                                 closeOnEscape: true,
+                                 buttons: { "OK": function() {
+                                                     var myPromptText = $("#myPromptText").val();
+                                                     $(this).dialog("close");
+                                                     callback(myPromptText);
+                                                 }
+                                         }
+                             });
+     },
  
- function mapMouseDown(e)
- {
-     // XXXX Is rightclick logic necessary?
-     var rightclick = e.which ? (e.which == 3) : (e.button == 2);
-     if(rightclick)
+     hit: function (menuItemClicked, menuObject, cmd, args)
      {
-         return false;
-     } else {
-         var o = findMapItem(e);
-         if(o) {
-             // XXXX Why does href get changed to "about://" on IE?
-             window.location = o.href;
+         setTimeout( function() {
+                         rightClick.hitFinish(menuItemClicked, menuObject, cmd, args);
+                     }, 1);
+     },
+ 
+     hitFinish: function (menuItemClicked, menuObject, cmd, args)
+     {   // dispatcher for context menu hits
+         var id = rightClick.selectedMenuItem.id;
+         if(menuObject.shown) {
+             // showWarning("Spinning: menu is still shown");
+             setTimeout(function() { rightClick.hitFinish(menuItemClicked, menuObject, cmd); }, 10);
+             return;
          }
-         return true;
-     }
- }
- 
- function contextMenuHit(menuItemClicked, menuObject, cmd, args)
- {
-     setTimeout(function() { contextMenuHitFinish(menuItemClicked, menuObject, cmd, args); }, 1);
- }
- 
- function contextMenuHitFinish(menuItemClicked, menuObject, cmd, args)
- {
- // dispatcher for context menu hits
-     var id = selectedMenuItem.id;
-     if(menuObject.shown) {
-         // showWarning("Spinning: menu is still shown");
-         setTimeout(function() { contextMenuHitFinish(menuItemClicked, menuObject, cmd); }, 10);
-         return;
-     }
-     if(cmd == 'selectWholeGene' || cmd == 'getDna') {
-             // bring whole gene into view or redirect to DNA screen.
-             var href = selectedMenuItem.href;
-             var chromStart, chromEnd;
-             var a = /hgg_chrom=(\w+)&/.exec(href);
-             // Many links leave out the chrom (b/c it's in the server side cart as "c")
-             var chrom = hgTracks.chromName;
-             if(a) {
-                 if(a && a[1])
-                     chrom = a[1];
-                 a = /hgg_start=(\d+)/.exec(href);
-                 if(a && a[1])
-                     // XXXX does chromStart have to be incremented by 1?
-                     chromStart = a[1];
-                 a = /hgg_end=(\d+)/.exec(href);
-                 if(a && a[1])
-                     chromEnd = a[1];
-             } else {
-                 // a = /hgc.*\W+c=(\w+)/.exec(href);
-                 a = /hgc.*\W+c=(\w+)/.exec(href);
-                 if(a && a[1])
-                     chrom = a[1];
-                 a = /o=(\d+)/.exec(href);
-                 if(a && a[1])
-                     chromStart = parseInt(a[1]) + 1;
-                 a = /t=(\d+)/.exec(href);
-                 if(a && a[1])
-                     chromEnd = parseInt(a[1]);
-             }
-             if(chrom == null || chromStart == null || chromEnd == null) {
-                 showWarning("couldn't parse out genomic coordinates");
-             } else {
-                 if(cmd == 'getDna')
-                 {
-                     if(window.open("../cgi-bin/hgc?g=getDna&i=mixed&c=" + chrom + "&l=" + (chromStart - 1) + "&r=" + chromEnd) == null) {
-                         windowOpenFailedMsg();
-                     }
+         if(cmd == 'selectWholeGene' || cmd == 'getDna') {
+                 // bring whole gene into view or redirect to DNA screen.
+                 var href = rightClick.selectedMenuItem.href;
+                 var chromStart, chromEnd;
+                 var a = /hgg_chrom=(\w+)&/.exec(href);
+                 // Many links leave out the chrom (b/c it's in the server side cart as "c")
+                 var chrom = hgTracks.chromName;
+                 if(a) {
+                     if(a && a[1])
+                         chrom = a[1];
+                     a = /hgg_start=(\d+)/.exec(href);
+                     if(a && a[1])
+                         // XXXX does chromStart have to be incremented by 1?
+                         chromStart = a[1];
+                     a = /hgg_end=(\d+)/.exec(href);
+                     if(a && a[1])
+                         chromEnd = a[1];
+                 } else {
+                     // a = /hgc.*\W+c=(\w+)/.exec(href);
+                     a = /hgc.*\W+c=(\w+)/.exec(href);
+                     if(a && a[1])
+                         chrom = a[1];
+                     a = /o=(\d+)/.exec(href);
+                     if(a && a[1])
+                         chromStart = parseInt(a[1]) + 1;
+                     a = /t=(\d+)/.exec(href);
+                     if(a && a[1])
+                         chromEnd = parseInt(a[1]);
+                 }
+                 if(chrom == null || chromStart == null || chromEnd == null) {
+                     showWarning("couldn't parse out genomic coordinates");
                  } else {
-                     var newPosition = setPositionByCoordinates(chrom, chromStart, chromEnd);
-                     var reg = new RegExp("hgg_gene=([^&]+)");
-                     var a = reg.exec(href);
-                     var name;
-                     // pull item name out of the url so we can set hgFind.matches (redmine 3062)
-                     if(a && a[1]) {
-                         name = a[1];
+                     if(cmd == 'getDna')
+                     {
+                         if(window.open("../cgi-bin/hgc?g=getDna&i=mixed&c=" +
+                                         chrom + "&l=" + (chromStart - 1) + "&r=" + chromEnd
+                                       ) == null) {
+                             rightClick.windowOpenFailedMsg();
+                         }
                      } else {
-                         reg = new RegExp("[&?]i=([^&]+)");
-                         a = reg.exec(href);
+                         var newPosition = genomePos.setByCoordinates(chrom, chromStart, chromEnd);
+                         var reg = new RegExp("hgg_gene=([^&]+)");
+                         var a = reg.exec(href);
+                         var name;
+                         // pull item name out of the url so we can set hgFind.matches (redmine 3062)
                          if(a && a[1]) {
                              name = a[1];
+                         } else {
+                             reg = new RegExp("[&?]i=([^&]+)");
+                             a = reg.exec(href);
+                             if(a && a[1]) {
+                                 name = a[1];
+                             }
+                         }
+                         if(imageV2.inPlaceUpdate) {
+                             // XXXX This attempt to "update whole track image in place" didn't work for a variety of reasons
+                             // (e.g. safari doesn't parse map when we update on the client side), so this is currently dead code.
+                             // However, this now works in all other browsers, so we may turn this on for non-safari browsers
+                             // (see redmine #4667).
+                             jQuery('body').css('cursor', '');
+                             var data = "hgt.trackImgOnly=1&hgt.ideogramToo=1&position=" +
+                                        newPosition + "&hgsid=" + getHgsid();
+                             if(name)
+                                 data += "&hgFind.matches=" + name;
+                             $.ajax({
+                                     type: "GET",
+                                     url: "../cgi-bin/hgTracks",
+                                     data: data,
+                                     dataType: "html",
+                                     trueSuccess: imageV2.updateImgAndMap,
+                                     success: catchErrorOrDispatch,
+                                     error: errorHandler,
+                                     cmd: cmd,
+                                     loadingId: showLoadingImage("imgTbl"),
+                                     cache: false
+                                 });
+                         } else {
+                             // do a full page refresh to update hgTracks image
+                             jQuery('body').css('cursor', 'wait');
+                             var ele;
+                             if(document.TrackForm)
+                                 ele = document.TrackForm;
+                             else
+                                 ele = document.TrackHeaderForm;
+                             if(name)
+                                 $(ele).append("<input type='hidden' name='hgFind.matches' " +
+                                               "value='" + name + "'>");
+                             ele.submit();
                          }
-                     }
-                     if(inPlaceUpdate) {
-                         // XXXX This attempt to "update whole track image in place" didn't work for a variety of reasons
-                         // (e.g. safari doesn't parse map when we update on the client side), so this is currently dead code.
-                         // However, this now works in all other browsers, so we may turn this on for non-safari browsers
-                         // (see redmine #4667).
-                         jQuery('body').css('cursor', '');
-                         var data = "hgt.trackImgOnly=1&hgt.ideogramToo=1&position=" + newPosition + "&hgsid=" + getHgsid();
-                         if(name)
-                             data += "&hgFind.matches=" + name;
-                         $.ajax({
-                                    type: "GET",
-                                    url: "../cgi-bin/hgTracks",
-                                    data: data,
-                                    dataType: "html",
-                                    trueSuccess: handleUpdateTrackMap,
-                                    success: catchErrorOrDispatch,
-                                    error: errorHandler,
-                                    cmd: cmd,
-                                    loadingId: showLoadingImage("imgTbl"),
-                                    cache: false
-                                });
-                     } else {
-                         // do a full page refresh to update hgTracks image
-                         jQuery('body').css('cursor', 'wait');
-                         var ele;
-                         if(document.TrackForm)
-                             ele = document.TrackForm;
-                         else
-                             ele = document.TrackHeaderForm;
-                         if(name)
-                             $(ele).append("<input type='hidden' name='hgFind.matches' value='" + name + "'>");
-                         ele.submit();
                      }
                  }
-             }
-     } else if (cmd == 'zoomCodon' || cmd == 'zoomExon') {
-         var num, ajaxCmd, msg;
-         if(cmd == 'zoomCodon') {
-             msg = "Please enter the codon number to jump to:";
-             ajaxCmd = 'codonToPos';
-         } else {
-             msg = "Please enter the exon number to jump to:";
-             ajaxCmd = 'exonToPos';
-         }
-         myPrompt(msg, function(results) {
-             $.ajax({
-                        type: "GET",
-                        url: "../cgi-bin/hgApi",
-                        data: "db=" + getDb() +  "&cmd=" + ajaxCmd + "&num=" + results + "&table=" + args.table + "&name=" + args.name,
-                        trueSuccess: handleZoomCodon,
-                        success: catchErrorOrDispatch,
-                        error: errorHandler,
-                        cache: true
-                    });
-                  });
-     } else if (cmd == 'hgTrackUi_popup') {
- 
-         hgTrackUiPopUp( selectedMenuItem.id, false );  // Launches the popup but shields the ajax with a waitOnFunction
- 
-     } else if (cmd == 'hgTrackUi_follow') {
- 
-         var url = "hgTrackUi?hgsid=" + getHgsid() + "&g=";
-         var rec = hgTracks.trackDb[id];
-         if (tdbHasParent(rec) && tdbIsLeaf(rec))
-             url += rec.parentTrack
-         else {
-             var link = $( 'td#td_btn_'+ selectedMenuItem.id ).children('a'); // The button already has the ref
-             if( $(link) != undefined)
-                 url = $(link).attr('href');
-             else
-                 url += selectedMenuItem.id;
-         }
-         location.assign(url);
- 
-     } else if (cmd == 'dragZoomMode') {
-         autoHideSetting = true;
-         var obj = imgAreaSelect.data('imgAreaSelect');
-         obj.setOptions({autoHide : true, movable: false});
-     } else if (cmd == 'hilightMode') {
-         autoHideSetting = false;
-         var obj = imgAreaSelect.data('imgAreaSelect');
-         obj.setOptions({autoHide : false, movable: true});
-     } else if (cmd == 'viewImg') {
-         // Fetch a new copy of track img and show it to the user in another window. This code assume we have updated
-         // remote cart with all relevant chages (e.g. drag-reorder).
-         var data = "hgt.imageV1=1&hgt.trackImgOnly=1&hgsid=" + getHgsid();
-         jQuery('body').css('cursor', 'wait');
-         $.ajax({
-                    type: "GET",
-                    url: "../cgi-bin/hgTracks",
-                    data: data,
-                    dataType: "html",
-                    trueSuccess: handleViewImg,
-                    success: catchErrorOrDispatch,
-                    error: errorHandler,
-                    cmd: cmd,
-                    cache: false
-                });
-     } else if (cmd == 'openLink' || cmd == 'followLink') {
-         var href = selectedMenuItem.href;
-         var vars = new Array("c", "l", "r", "db");
-         var valNames = new Array("chromName", "winStart", "winEnd");
-         for (var i in vars) {
-             // make sure the link contains chrom and window width info (necessary b/c we are stripping hgsid and/or the cart may be empty);
-             // but don't add chrom to wikiTrack links (see redmine #2476).
-             var v = vars[i];
-             var val;
-             if(v == "db") {
-                 val = getDb();
+         } else if (cmd == 'zoomCodon' || cmd == 'zoomExon') {
+             var num, ajaxCmd, msg;
+             if(cmd == 'zoomCodon') {
+                 msg = "Please enter the codon number to jump to:";
+                 ajaxCmd = 'codonToPos';
              } else {
-                 val = hgTracks[valNames[i]];
+                 msg = "Please enter the exon number to jump to:";
+                 ajaxCmd = 'exonToPos';
              }
-             if(val && id != "wikiTrack" && (href.indexOf("?" + v + "=") == -1) && (href.indexOf("&" + v + "=") == -1)) {
-                 href = href + "&" + v + "=" + val;
-             }
-         }
-         if(cmd == 'followLink') {
-             // XXXX This is blocked by Safari's popup blocker (without any warning message).
-             location.assign(href);
-         } else {
-             // Remove hgsid to force a new session (see redmine ticket 1333).
-             href = removeHgsid(href);
-             if(window.open(href) == null) {
-                 windowOpenFailedMsg();
+             rightClick.myPrompt(msg, function(results) {
+                 $.ajax({
+                         type: "GET",
+                         url: "../cgi-bin/hgApi",
+                         data: "db=" + getDb() +  "&cmd=" + ajaxCmd + "&num=" + results +
+                               "&table=" + args.table + "&name=" + args.name,
+                         trueSuccess: rightClick.handleZoomCodon,
+                         success: catchErrorOrDispatch,
+                         error: errorHandler,
+                         cache: true
+                     });
+                     });
+         } else if (cmd == 'hgTrackUi_popup') {
+ 
+             popUp.hgTrackUi( rightClick.selectedMenuItem.id, false );  // Launches the popup but shields the ajax with a waitOnFunction
+ 
+         } else if (cmd == 'hgTrackUi_follow') {
+ 
+             var url = "hgTrackUi?hgsid=" + getHgsid() + "&g=";
+             var rec = hgTracks.trackDb[id];
+             if (tdbHasParent(rec) && tdbIsLeaf(rec))
+                 url += rec.parentTrack
+             else {
+                 var link = $( 'td#td_btn_'+ rightClick.selectedMenuItem.id ).children('a'); // The button already has the ref
+                 if ($(link) != undefined)
+                     url = $(link).attr('href');
+                 else
+                     url += rightClick.selectedMenuItem.id;
              }
-         }
-     } else if (cmd == 'float') {
-         if(floatingMenuItem && floatingMenuItem == id) {
-             $.floatMgr.FOArray = new Array();
-             floatingMenuItem = null;
-         } else {
-             if(floatingMenuItem) {
-                 // This doesn't work.
-                 $('#img_data_' + floatingMenuItem).parent().restartFloat();
-                 // This does work
-                 $.floatMgr.FOArray = new Array();
+             location.assign(url);
+ 
+         } else if (cmd == 'dragZoomMode') {
+             dragSelect.autoHideSetting = true;
+             var obj = dragSelect.areaSelector.data('imgAreaSelect');
+             obj.setOptions({autoHide : true, movable: false});
+         } else if (cmd == 'hilightMode') {
+             dragSelect.autoHideSetting = false;
+             var obj = dragSelect.areaSelector.data('imgAreaSelect');
+             obj.setOptions({autoHide : false, movable: true});
+         } else if (cmd == 'viewImg') {
+             // Fetch a new copy of track img and show it to the user in another window. This code assume we have updated
+             // remote cart with all relevant chages (e.g. drag-reorder).
+             var data = "hgt.imageV1=1&hgt.trackImgOnly=1&hgsid=" + getHgsid();
+             jQuery('body').css('cursor', 'wait');
+             $.ajax({
+                     type: "GET",
+                     url: "../cgi-bin/hgTracks",
+                     data: data,
+                     dataType: "html",
+                     trueSuccess: rightClick.handleViewImg,
+                     success: catchErrorOrDispatch,
+                     error: errorHandler,
+                     cmd: cmd,
+                     cache: false
+                 });
+         } else if (cmd == 'openLink' || cmd == 'followLink') {
+             var href = rightClick.selectedMenuItem.href;
+             var vars = new Array("c", "l", "r", "db");
+             var valNames = new Array("chromName", "winStart", "winEnd");
+             for (var i in vars) {
+                 // make sure the link contains chrom and window width info (necessary b/c we are stripping hgsid and/or the cart may be empty);
+                 // but don't add chrom to wikiTrack links (see redmine #2476).
+                 var v = vars[i];
+                 var val;
+                 if(v == "db") {
+                     val = getDb();
+                 } else {
+                     val = hgTracks[valNames[i]];
+                 }
+                 if (val
+                 && id != "wikiTrack"
+                 && (href.indexOf("?" + v + "=") == -1)
+                 && (href.indexOf("&" + v + "=") == -1)) {
+                     href = href + "&" + v + "=" + val;
+                 }
              }
-             floatingMenuItem = id;
-             reloadFloatingItem();
-             updateTrackImg(id, "hgt.transparentImage=0", "");
-         }
-     } else if (cmd == 'hideSet') {
-         var row = $( 'tr#tr_' + id );
-         var rows = imgTblContiguousRowSet(row);
-         if (rows && rows.length > 0) {
-             var vars = new Array();
-             var vals = new Array();
-             for (var ix=rows.length - 1; ix >= 0; ix--) { // from bottom, just in case remove screws with us
-                 var rowId = $(rows[ix]).attr('id').substring('tr_'.length);
-                 //if (tdbIsSubtrack(hgTracks.trackDb[rowId]) == false)
-                 //    warn('What went wrong?');
- 
-                 vars.push(rowId, rowId+'_sel'); // Remove subtrack level vis and explicitly uncheck.
-                 vals.push('[]', 0);
-                 $(rows[ix]).remove();
+             if(cmd == 'followLink') {
+                 // XXXX This is blocked by Safari's popup blocker (without any warning message).
+                 location.assign(href);
+             } else {
+                 // Remove hgsid to force a new session (see redmine ticket 1333).
+                 href = removeHgsid(href);
+                 if(window.open(href) == null) {
+                     rightClick.windowOpenFailedMsg();
+                 }
              }
-             if (vars.length > 0) {
-                 setCartVars( vars, vals );
-                 initImgTblButtons();
-                 loadImgAreaSelect(false);
+         } else if (cmd == 'float') {
+             if(rightClick.floatingMenuItem && rightClick.floatingMenuItem == id) {
+                 $.floatMgr.FOArray = new Array();
+                 rightClick.floatingMenuItem = null;
+             } else {
+                 if(rightClick.floatingMenuItem) {
+                     // This doesn't work.
+                     $('#img_data_' + rightClick.floatingMenuItem).parent().restartFloat();
+                     // This does work
+                     $.floatMgr.FOArray = new Array();
+                 }
+                 rightClick.floatingMenuItem = id;
+                 rightClick.reloadFloatingItem();
+                 imageV2.requestImgUpdate(id, "hgt.transparentImage=0", "");
              }
-             markAsDirtyPage();
-         }
-     } else if (cmd == 'hideComposite') {
-         var rec = hgTracks.trackDb[id];
-         if (tdbIsSubtrack(rec)) {
+         } else if (cmd == 'hideSet') {
              var row = $( 'tr#tr_' + id );
-             var rows = imgTblCompositeSet(row);
+             var rows = dragReorder.getContiguousRowSet(row);
              if (rows && rows.length > 0) {
+                 var vars = new Array();
+                 var vals = new Array();
                  for (var ix=rows.length - 1; ix >= 0; ix--) { // from bottom, just in case remove screws with us
+                     var rowId = $(rows[ix]).attr('id').substring('tr_'.length);
+                     //if (tdbIsSubtrack(hgTracks.trackDb[rowId]) == false)
+                     //    warn('What went wrong?');
+ 
+                     vars.push(rowId, rowId+'_sel'); // Remove subtrack level vis and explicitly uncheck.
+                     vals.push('[]', 0);
                      $(rows[ix]).remove();
                  }
-             var selectUpdated = updateVisibility(rec.parentTrack, 'hide');
-             setCartVar(rec.parentTrack, 'hide' );
-             initImgTblButtons();
-             loadImgAreaSelect(false);
-             markAsDirtyPage();
+                 if (vars.length > 0) {
+                     setCartVars( vars, vals );
+                     dragReorder.init();
+                     dragSelect.load(false);
+                 }
+                 imageV2.markAsDirtyPage();
              }
-         }
-         //else
-         //    warn('What went wrong?');
-     } else {   // if( cmd in 'hide','dense','squish','pack','full','show' )
-         // Change visibility settings:
-         //
-         // First change the select on our form:
-         var rec = hgTracks.trackDb[id];
-         var selectUpdated = updateVisibility(id, cmd);
- 
-         // Now change the track image
-         if(imageV2 && cmd == 'hide')
-         {
-             // Hide local display of this track and update server side cart.
-             // Subtracks controlled by 2 settings so del vis and set sel=0.  Others, just set vis hide.
-             if(tdbIsSubtrack(rec))
-                 setCartVars( [ id, id+"_sel" ], [ '[]', 0 ] ); // Remove subtrack level vis and explicitly uncheck.
-             else if(tdbIsFolderContent(rec))
-                 setCartVars( [ id, id+"_sel" ], [ 'hide', 0 ] ); // supertrack children need to have _sel set to trigger superttrack reshaping
-             else
-                 setCartVar(id, 'hide' );
-             $('#tr_' + id).remove();
-             initImgTblButtons();
-             loadImgAreaSelect(false);
-             markAsDirtyPage();
-         } else if (!mapIsUpdateable) {
-             jQuery('body').css('cursor', 'wait');
-             if(selectUpdated) {
-                 // assert(document.TrackForm);
-                 document.TrackForm.submit();
-             } else {
-                     // add a hidden with new visibility value
-                     var form = $(document.TrackHeaderForm);
-                     $("<input type='hidden' name='" + id + "'value='" + cmd + "'>").appendTo(form);
-                     document.TrackHeaderForm.submit();
+         } else if (cmd == 'hideComposite') {
+             var rec = hgTracks.trackDb[id];
+             if (tdbIsSubtrack(rec)) {
+                 var row = $( 'tr#tr_' + id );
+                 var rows = dragReorder.getCompositeSet(row);
+                 if (rows && rows.length > 0) {
+                     for (var ix=rows.length - 1; ix >= 0; ix--) { // from bottom, just in case remove screws with us
+                         $(rows[ix]).remove();
+                     }
+                 var selectUpdated = vis.update(rec.parentTrack, 'hide');
+                 setCartVar(rec.parentTrack, 'hide' );
+                 dragReorder.init();
+                 dragSelect.load(false);
+                 imageV2.markAsDirtyPage();
+                 }
              }
-         } else {
-             var data = "hgt.trackImgOnly=1&" + id + "=" + cmd + "&hgsid=" + getHgsid();  // this will update vis in remote cart
-             if(imageV2) {
- 	        data += "&hgt.trackNameFilter=" + id;
+             //else
+             //    warn('What went wrong?');
+         } else {   // if ( cmd in 'hide','dense','squish','pack','full','show' )
+             // Change visibility settings:
+             //
+             // First change the select on our form:
+             var rec = hgTracks.trackDb[id];
+             var selectUpdated = vis.update(id, cmd);
+ 
+             // Now change the track image
+             if(imageV2.enabled && cmd == 'hide')
+             {
+                 // Hide local display of this track and update server side cart.
+                 // Subtracks controlled by 2 settings so del vis and set sel=0.  Others, just set vis hide.
+                 if(tdbIsSubtrack(rec))
+                     setCartVars( [ id, id+"_sel" ], [ '[]', 0 ] ); // Remove subtrack level vis and explicitly uncheck.
+                 else if(tdbIsFolderContent(rec))
+                     setCartVars( [ id, id+"_sel" ], [ 'hide', 0 ] ); // supertrack children need to have _sel set to trigger superttrack reshaping
+                 else
+                     setCartVar(id, 'hide' );
+                 $('#tr_' + id).remove();
+                 dragReorder.init();
+                 dragSelect.load(false);
+                 imageV2.markAsDirtyPage();
+             } else if (!imageV2.mapIsUpdateable) {
+                 jQuery('body').css('cursor', 'wait');
+                 if(selectUpdated) {
+                     // assert(document.TrackForm);
+                     document.TrackForm.submit();
+                 } else {
+                         // add a hidden with new visibility value
+                         var form = $(document.TrackHeaderForm);
+                         $("<input type='hidden' name='"+id+"'value='"+cmd+"'>").appendTo(form);
+                         document.TrackHeaderForm.submit();
+                 }
+             } else {
+                 imageV2.requestImgUpdate(id, id+"="+cmd, "");
+                 /*var data = "hgt.trackImgOnly=1&" + id + "=" + cmd + "&hgsid=" + getHgsid();  // this will update vis in remote cart
+                 if(imageV2.enabled) {
+                     data += "&hgt.trackNameFilter=" + id;
+                 }
+                 //var center = $("#img_data_" + id);
+                 //center.attr('src', "../images/loading.gif")
+                 //center.attr('style', "text-align: center; display: block;");
+                 //warn("hgTracks?"+data); // Uesful to cut and paste the url
+                 var loadingId = showLoadingImage("tr_" + id);
+                 $.ajax({
+                         type: "GET",
+                         url: "../cgi-bin/hgTracks",
+                         data: data,
+                         dataType: "html",
+                         trueSuccess: imageV2.updateImgAndMap,
+                         success: catchErrorOrDispatch,
+                         error: errorHandler,
+                         cmd: cmd,
+                         newVisibility: cmd,
+                         id: id,
+                         loadingId: loadingId,
+                         cache: false
+                     });*/
              }
-             //var center = $("#img_data_" + id);
-             //center.attr('src', "../images/loading.gif")
-             //center.attr('style', "text-align: center; display: block;");
-             //warn("hgTracks?"+data); // Uesful to cut and paste the url
-             var loadingId = showLoadingImage("tr_" + id);
-             $.ajax({
-                        type: "GET",
-                        url: "../cgi-bin/hgTracks",
-                        data: data,
-                        dataType: "html",
-                        trueSuccess: handleUpdateTrackMap,
-                        success: catchErrorOrDispatch,
-                        error: errorHandler,
-                        cmd: cmd,
-                        newVisibility: cmd,
-                        id: id,
-                        loadingId: loadingId,
-                        cache: false
-                    });
          }
-     }
- }
+     },
  
- function myPrompt(msg, callback)
- {
- // replacement for prompt; avoids misleading/confusing security warnings which are caused by prompt in IE 7+
- // callback is called if user presses "OK".
-     $("body").append("<div id = 'myPrompt'><div id='dialog' title='Basic dialog'><form>" + msg + "<input id='myPromptText' value=''></form>");
-     $("#myPrompt").dialog({
-                               modal: true,
-                               closeOnEscape: true,
-                               buttons: { "OK": function() {
-                                                             var myPromptText = $("#myPromptText").val();
-                                                             $(this).dialog("close");
-                                                             callback(myPromptText);
-                                                           }
-                                        }
-                           });
- }
+     makeHitCallback: function (title)
+     {   // stub to avoid problem with a function closure w/n a loop
+         return function(menuItemClicked, menuObject) {
+             rightClick.hit(menuItemClicked, menuObject, title); return true;
+         };
+     },
  
- function makeContextMenuHitCallback(title)
- {
- // stub to avoid problem with a function closure w/n a loop
-     return function(menuItemClicked, menuObject) {
-         contextMenuHit(menuItemClicked, menuObject, title); return true;
-     };
- }
+     reloadFloatingItem: function ()
+     {   // currently dead (experimental code)
+         if(rightClick.floatingMenuItem) {
+             $('#img_data_' + rightClick.floatingMenuItem).parent().makeFloat(
+                 {x:"current",y:"current", speed: 'fast', alwaysVisible: true, alwaysTop: true});
+         }
+     },
  
- function makeImgTag(img)
- {
- // Return img tag with explicit dimensions for img (dimensions are currently hardwired).
- // This fixes the "weird shadow problem when first loading the right-click menu" seen in FireFox 3.X,
- // which occurred b/c FF doesn't actually fetch the image until the menu is being shown.
-     return "<img style='width:16px; height:16px; border-style:none;' src='../images/" + img + "' />";
- }
+     makeImgTag: function (img)
+     {   // Return img tag with explicit dimensions for img (dimensions are currently hardwired).
+         // This fixes the "weird shadow problem when first loading the right-click menu" seen in FireFox 3.X,
+         // which occurred b/c FF doesn't actually fetch the image until the menu is being shown.
+         return "<img style='width:16px; height:16px; border-style:none;' src='../images/" +
+                 img + "' />";
+     },
  
- function loadContextMenu(img)
- {
-     contextMenu = img.contextMenu(
-         function() {
-             popUpBoxCleanup();   // Popup box is not getting closed properly so must do it here
- 
-             var menu = [];
-             var selectedImg = makeImgTag("greenChecksm.png");
-             var blankImg    = makeImgTag("invisible16.png");
-             var done = false;
-             if(selectedMenuItem && selectedMenuItem.id != null) {
-                 var href = selectedMenuItem.href;
-                 var isHgc, isGene;
-                 if(href) {
-                     isGene = href.match("hgGene");
-                     isHgc = href.match("hgc");
-                 }
-                 var id = selectedMenuItem.id;
-                 var rec = hgTracks.trackDb[id];
-                 var offerHideSubset    = false;
-                 var offerHideComposite = false;
-                 var offerSingles       = true;
-                 var row = $( 'tr#tr_' + id );
-                 if (row) {
-                     var btn = $(row).find('p.btnBlue');  // btnBlue means cursor over left button
-                     if (btn.length == 1) {
-                         var compositeSet = imgTblCompositeSet(row);
-                         if (compositeSet && compositeSet.length > 0) {  // There is a composite set
-                             offerHideComposite = true;
-                             $( compositeSet ).find('p.btn').addClass('blueButtons');  // blue persists
  
-                             var subSet = imgTblContiguousRowSet(row);
-                             if (subSet && subSet.length > 1) {
-                                 offerSingles = false;
-                                 if(subSet.length < compositeSet.length) {
-                                     offerHideSubset = true;
-                                     $( subSet ).addClass("greenRows"); // green persists
+     load: function (img)
+     {
+         rightClick.menu = img.contextMenu(
+             function() {
+                 popUp.cleanup();   // Popup box is not getting closed properly so must do it here
+ 
+                 var menu = [];
+                 var selectedImg = rightClick.makeImgTag("greenChecksm.png");
+                 var blankImg    = rightClick.makeImgTag("invisible16.png");
+                 var done = false;
+                 if(rightClick.selectedMenuItem && rightClick.selectedMenuItem.id != null) {
+                     var href = rightClick.selectedMenuItem.href;
+                     var isHgc, isGene;
+                     if(href) {
+                         isGene = href.match("hgGene");
+                         isHgc = href.match("hgc");
+                     }
+                     var id = rightClick.selectedMenuItem.id;
+                     var rec = hgTracks.trackDb[id];
+                     var offerHideSubset    = false;
+                     var offerHideComposite = false;
+                     var offerSingles       = true;
+                     var row = $( 'tr#tr_' + id );
+                     if (row) {
+                         var btn = $(row).find('p.btnBlue');  // btnBlue means cursor over left button
+                         if (btn.length == 1) {
+                             var compositeSet = dragReorder.getCompositeSet(row);
+                             if (compositeSet && compositeSet.length > 0) {  // There is a composite set
+                                 offerHideComposite = true;
+                                 $( compositeSet ).find('p.btn').addClass('blueButtons');  // blue persists
+ 
+                                 var subSet = dragReorder.getContiguousRowSet(row);
+                                 if (subSet && subSet.length > 1) {
+                                     offerSingles = false;
+                                     if(subSet.length < compositeSet.length) {
+                                         offerHideSubset = true;
+                                         $( subSet ).addClass("greenRows"); // green persists
+                                     }
                                  }
                              }
                          }
                      }
-                 }
  
-                 // First option is hide sets
-                 if (offerHideComposite) {
-                     if (offerHideSubset) {
+                     // First option is hide sets
+                     if (offerHideComposite) {
+                         if (offerHideSubset) {
+                             var o = new Object();
+                             o[blankImg + " hide track subset (green)"] = {
+                                                 onclick: rightClick.makeHitCallback('hideSet')};
+                             //o[rightClick.makeImgTag("highliteGreenX.png") + " hide track subset"] = {onclick: rightClick.makeHitCallback('hideSet')};
+                             menu.push(o);
+                         }
+ 
                          var o = new Object();
-                         o[blankImg + " hide track subset (green)"] = {onclick: makeContextMenuHitCallback('hideSet')};
-                         //o[makeImgTag("highliteGreenX.png") + " hide track subset"] = {onclick: makeContextMenuHitCallback('hideSet')};
+                         var str = blankImg + " hide track set";
+                         if (offerHideSubset)
+                             str += " (blue)";
+                         o[str] = {onclick: rightClick.makeHitCallback('hideComposite')};
+                         //o[rightClick.makeImgTag("btnBlueX.png") + " hide track set"] = {onclick: rightClick.makeHitCallback('hideComposite')};
                          menu.push(o);
                      }
  
-                     var o = new Object();
-                     var str = blankImg + " hide track set";
-                     if (offerHideSubset)
-                         str += " (blue)";
-                     o[str] = {onclick: makeContextMenuHitCallback('hideComposite')};
-                     //o[makeImgTag("btnBlueX.png") + " hide track set"] = {onclick: makeContextMenuHitCallback('hideComposite')};
-                     menu.push(o);
-                 }
- 
-                 // Second set of options: visibility for single track
-                 if (offerSingles) {
-                     if (offerHideComposite)
-                         menu.push($.contextMenu.separator);
- 
-                     // XXXX what if select is not available (b/c trackControlsOnMain is off)?
-                     // Move functionality to a hidden variable?
-                     var select = $("select[name=" + id + "]");
-                     if (select.length > 1)  // Not really needed if $('#hgTrackUiDialog').html(""); has worked
-                         select =  [ $(select)[0] ];
-                     var cur = $(select).val();
-                     if(cur) {
-                         $(select).children().each(function(index, o) {
-                                                 var title = $(this).val();
-                                                 var str = blankImg + " " + title;
-                                                 if(title == cur)
-                                                     str = selectedImg + " " + title;
-                                                 var o = new Object();
-                                                 o[str] = {onclick: function (menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, title); return true;}};
-                                                 menu.push(o);
-                                             });
-                         done = true;
-                     } else {
-                         if(rec) {
-                             // XXXX check current state from a hidden variable.
-                             var visibilityStrs = new Array("hide", "dense", "squish", "pack", "full");
-                             for (var i in visibilityStrs) {
-                                 // XXXX use maxVisibility and change hgTracks so it can hide subtracks
+                     // Second set of options: visibility for single track
+                     if (offerSingles) {
+                         if (offerHideComposite)
+                             menu.push($.contextMenu.separator);
+ 
+                         // XXXX what if select is not available (b/c trackControlsOnMain is off)?
+                         // Move functionality to a hidden variable?
+                         var select = $("select[name=" + id + "]");
+                         if (select.length > 1)  // Not really needed if $('#hgTrackUiDialog').html(""); has worked
+                             select =  [ $(select)[0] ];
+                         var cur = $(select).val();
+                         if(cur) {
+                             $(select).children().each(function(index, o) {
+                                 var title = $(this).val();
+                                 var str = blankImg + " " + title;
+                                 if(title == cur)
+                                     str = selectedImg + " " + title;
                                  var o = new Object();
-                                 var str = blankImg + " " + visibilityStrs[i];
-                                 if(rec.canPack || (visibilityStrs[i] != "pack" && visibilityStrs[i] != "squish")) {
-                                     if(rec.localVisibility) {
-                                         if(visibilityStrs[i] == rec.localVisibility) {
-                                             str = selectedImg + " " + visibilityStrs[i];
+                                 o[str] = {onclick: function (menuItemClicked, menuObject) {
+                                             rightClick.hit(menuItemClicked, menuObject, title);
+                                             return true;}};
+                                 menu.push(o);
+                             });
+                             done = true;
+                         } else {
+                             if(rec) {
+                                 // XXXX check current state from a hidden variable.
+                                 var visStrings = new Array("hide","dense","squish","pack","full");
+                                 for (var i in visStrings) {
+                                     // XXXX use maxVisibility and change hgTracks so it can hide subtracks
+                                     var o = new Object();
+                                     var str = blankImg + " " + visStrings[i];
+                                     if (rec.canPack
+                                     || (visStrings[i] != "pack" && visStrings[i] != "squish")) {
+                                         if(rec.localVisibility) {
+                                             if(visStrings[i] == rec.localVisibility) {
+                                                 str = selectedImg + " " + visStrings[i];
+                                             }
+                                         } else if(visStrings[i] == vis.enumOrder[rec.visibility]) {
+                                             str = selectedImg + " " + visStrings[i];
                                          }
-                                     } else if(visibilityStrs[i] == visibilityStrsOrder[rec.visibility]) {
-                                         str = selectedImg + " " + visibilityStrs[i];
+                                         o[str] = { onclick:
+                                                     rightClick.makeHitCallback(visStrings[i])
+                                                  };
+                                         menu.push(o);
                                      }
-                                     o[str] = {onclick: makeContextMenuHitCallback(visibilityStrs[i])};
-                                     menu.push(o);
                                  }
+                                 done = true;
                              }
-                             done = true;
                          }
                      }
-                 }
  
-                 if(done) {
-                     var o = new Object();
-                     var any = false;
-                         var title = selectedMenuItem.title || "feature";
-                     if(isGene || isHgc || id == "wikiTrack") {
-                         // Add "Open details..." item
-                         var displayItemFunctions = false;
-                         if(rec) {
-                             if(rec.type.indexOf("wig") == 0 || rec.type.indexOf("bigWig") == 0 || id == "wikiTrack") {
-                                 displayItemFunctions = false;
-                             } else if(rec.type.indexOf("expRatio") == 0) {
-                                 displayItemFunctions = title != "zoomInMore";
-                             } else {
-                                 displayItemFunctions = true;
-                             }
-                         }
-                         if(displayItemFunctions) {
-                             o[makeImgTag("magnify.png") + " Zoom to " +  title] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "selectWholeGene"); return true; }};
-                             if(supportZoomCodon && rec.type.indexOf("genePred") != -1) {
-                                 // http://hgwdev-larrym.cse.ucsc.edu/cgi-bin/hgGene?hgg_gene=uc003tqk.2&hgg_prot=P00533&hgg_chrom=chr7&hgg_start=55086724&hgg_end=55275030&hgg_type=knownGene&db=hg19&c=chr7
-                                 var name, table;
-                                 var reg = new RegExp("hgg_gene=([^&]+)");
-                                 var a = reg.exec(href);
-                                 if(a && a[1]) {
-                                     name = a[1];
-                                     reg = new RegExp("hgg_type=([^&]+)");
-                                     a = reg.exec(href);
-                                     if(a && a[1]) {
-                                         table = a[1];
-                                     }
+                     if(done) {
+                         var o = new Object();
+                         var any = false;
+                             var title = rightClick.selectedMenuItem.title || "feature";
+                         if(isGene || isHgc || id == "wikiTrack") {
+                             // Add "Open details..." item
+                             var displayItemFunctions = false;
+                             if(rec) {
+                                 if(rec.type.indexOf("wig") == 0 || rec.type.indexOf("bigWig") == 0 || id == "wikiTrack") {
+                                     displayItemFunctions = false;
+                                 } else if(rec.type.indexOf("expRatio") == 0) {
+                                     displayItemFunctions = title != "zoomInMore";
                                  } else {
-                                     // http://hgwdev-larrym.cse.ucsc.edu/cgi-bin/hgc?o=55086724&t=55275031&g=refGene&i=NM_005228&c=chr7
-                                     // http://hgwdev-larrym.cse.ucsc.edu/cgi-bin/hgc?o=55086713&t=55270769&g=wgEncodeGencodeManualV4&i=ENST00000455089&c=chr7
-                                     var reg = new RegExp("i=([^&]+)");
+                                     displayItemFunctions = true;
+                                 }
+                             }
+                             if(displayItemFunctions) {
+                                 o[rightClick.makeImgTag("magnify.png") + " Zoom to " +  title] = {
+                                     onclick: function(menuItemClicked, menuObject) {
+                                                 rightClick.hit(menuItemClicked, menuObject,
+                                                         "selectWholeGene"); return true;
+                                               }
+                                     };
+                                 if(rightClick.supportZoomCodon && rec.type.indexOf("genePred") != -1) {
+                                     // http://hgwdev-larrym.cse.ucsc.edu/cgi-bin/hgGene?hgg_gene=uc003tqk.2&hgg_prot=P00533&hgg_chrom=chr7&hgg_start=55086724&hgg_end=55275030&hgg_type=knownGene&db=hg19&c=chr7
+                                     var name, table;
+                                     var reg = new RegExp("hgg_gene=([^&]+)");
                                      var a = reg.exec(href);
                                      if(a && a[1]) {
                                          name = a[1];
-                                         reg = new RegExp("g=([^&]+)");
+                                         reg = new RegExp("hgg_type=([^&]+)");
                                          a = reg.exec(href);
                                          if(a && a[1]) {
                                              table = a[1];
                                          }
+                                     } else {
+                                         // http://hgwdev-larrym.cse.ucsc.edu/cgi-bin/hgc?o=55086724&t=55275031&g=refGene&i=NM_005228&c=chr7
+                                         // http://hgwdev-larrym.cse.ucsc.edu/cgi-bin/hgc?o=55086713&t=55270769&g=wgEncodeGencodeManualV4&i=ENST00000455089&c=chr7
+                                         var reg = new RegExp("i=([^&]+)");
+                                         var a = reg.exec(href);
+                                         if(a && a[1]) {
+                                             name = a[1];
+                                             reg = new RegExp("g=([^&]+)");
+                                             a = reg.exec(href);
+                                             if(a && a[1]) {
+                                                 table = a[1];
+                                             }
+                                         }
+                                     }
+                                     if(name && table) {
+                                         o[rightClick.makeImgTag("magnify.png")+" Zoom to codon"] =
+                                         {   onclick: function(menuItemClicked, menuObject) {
+                                                 rightClick.hit(menuItemClicked, menuObject,
+                                                             "zoomCodon",
+                                                             {name: name, table: table});
+                                                 return true;}
+                                         };
+                                         o[rightClick.makeImgTag("magnify.png")+" Zoom to exon"] = {
+                                             onclick: function(menuItemClicked, menuObject) {
+                                                 rightClick.hit(menuItemClicked, menuObject,
+                                                               "zoomExon",
+                                                               {name: name, table: table});
+                                                 return true; }
+                                         };
                                      }
                                  }
-                                 if(name && table) {
-                                     o[makeImgTag("magnify.png") + " Zoom to codon"] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "zoomCodon", {name: name, table: table}); return true; }};
-                                     o[makeImgTag("magnify.png") + " Zoom to exon"] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "zoomExon", {name: name, table: table}); return true; }};
-                                 }
+                                 o[rightClick.makeImgTag("dnaIcon.png")+" Get DNA for "+title] = {
+                                     onclick: function(menuItemClicked, menuObject) {
+                                         rightClick.hit(menuItemClicked, menuObject, "getDna");
+                                         return true; }
+                                 };
                              }
-                             o[makeImgTag("dnaIcon.png") + " Get DNA for " +  title] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "getDna"); return true; }};
-                         }
-                         o[makeImgTag("bookOut.png") + " Open details page in new window..."] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "openLink"); return true; }};
-                         any = true;
-                     }
-                     if(href != undefined && href.length  > 0) {
-                         // Add "Show details..." item
-                         if(title.indexOf("Click to alter ") == 0) {
-                             ; // suppress the "Click to alter..." items
-                         } else if(selectedMenuItem.href.indexOf("cgi-bin/hgTracks") != -1) {
-                             ; // suppress menu items for hgTracks links (e.g. Next/Prev map items).
-                         } else {
-                             var item;
-                             if(title == "zoomInMore")
-                                 // avoid showing menu item that says "Show details for zoomInMore..." (redmine 2447)
-                                 item = makeImgTag("book.png") + " Show details...";
-                             else
-                                 item = makeImgTag("book.png") + " Show details for " + title + "...";
-                             o[item] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "followLink"); return true; }};
+                             o[rightClick.makeImgTag("bookOut.png")+
+                                                     " Open details page in new window..."] = {
+                                 onclick: function(menuItemClicked, menuObject) {
+                                     rightClick.hit(menuItemClicked, menuObject, "openLink");
+                                     return true; }
+                             };
                              any = true;
                          }
+                         if(href != undefined && href.length  > 0) {
+                             // Add "Show details..." item
+                             if(title.indexOf("Click to alter ") == 0) {
+                                 ; // suppress the "Click to alter..." items
+                             } else if(rightClick.selectedMenuItem.href.indexOf("cgi-bin/hgTracks") != -1) {
+                                 ; // suppress menu items for hgTracks links (e.g. Next/Prev map items).
+                             } else {
+                                 var item;
+                                 if(title == "zoomInMore")
+                                     // avoid showing menu item that says "Show details for zoomInMore..." (redmine 2447)
+                                     item = rightClick.makeImgTag("book.png") + " Show details...";
+                                 else
+                                     item = rightClick.makeImgTag("book.png")+" Show details for "+
+                                            title + "...";
+                                 o[item] = {onclick: function(menuItemClicked, menuObject) {
+                                            rightClick.hit(menuItemClicked,menuObject,"followLink");
+                                            return true; }
+                                 };
+                                 any = true;
+                             }
+                         }
+                         if(any) {
+                             menu.push($.contextMenu.separator);
+                             menu.push(o);
+                         }
                      }
-                     if(any) {
-                         menu.push($.contextMenu.separator);
+                 }
+                 if (!done) {
+                     if(false) {
+                         // Currently toggling b/n drag-and-zoom mode and hilite mode is disabled b/c we don't know how to keep hilite mode from disabling the
+                         // context menus.
+                         var o = new Object();
+                         var str = "drag-and-zoom mode";
+                         if(dragSelect.autoHideSetting) {
+                             str += selectedImg;
+                             // menu[str].className = 'context-menu-checked-item';
+                         }
+                         o[str] = { onclick: function(menuItemClicked, menuObject) {
+                                      rightClick.hit(menuItemClicked, menuObject, "dragZoomMode");
+                                      return true; }
+                                  };
+                         menu.push(o);
+                         o = new Object();
+                         // console.dir(ele);
+                         str = "hilight mode";
+                         if (!dragSelect.autoHideSetting) {
+                             str += selectedImg;
+                         }
+                         o[str] = { onclick: function(menuItemClicked, menuObject) {
+                                       rightClick.hit(menuItemClicked, menuObject, "hilightMode");
+                                       return true; }
+                                  };
                          menu.push(o);
                      }
+                     //menu.push({"view image": {onclick: function(menuItemClicked, menuObject) { rightClick.hit(menuItemClicked, menuObject, "viewImg"); return true; }}});
                  }
-             }
-             if(!done) {
-                 if(false) {
-                     // Currently toggling b/n drag-and-zoom mode and hilite mode is disabled b/c we don't know how to keep hilite mode from disabling the
-                     // context menus.
+ 
+                 if(rightClick.selectedMenuItem && rec && rec["configureBy"] != 'none') {
+                     // Add cfg options at just shy of end...
                      var o = new Object();
-                     var str = "drag-and-zoom mode";
-                     if(autoHideSetting) {
-                         str += selectedImg;
-                         // menu[str].className = 'context-menu-checked-item';
-                     }
-                     o[str] = { onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "dragZoomMode"); return true; }};
-                     menu.push(o);
-                     o = new Object();
-                     // console.dir(ele);
-                     str = "hilight mode";
-                     if(!autoHideSetting) {
-                         str += selectedImg;
+                     if(tdbIsLeaf(rec)) {
+                         o[rightClick.makeImgTag("wrench.png")+" Configure "+rec.shortLabel] = {
+                             onclick: function(menuItemClicked, menuObject) {
+                                 rightClick.hit(menuItemClicked, menuObject, "hgTrackUi_popup");
+                                 return true; }
+                         };
+                         if(rec.parentTrack != undefined)
+                             o[rightClick.makeImgTag("folderWrench.png")+" Configure "+
+                               rec.parentLabel + " track set..."] = {
+                                 onclick: function(menuItemClicked, menuObject) {
+                                     rightClick.hit(menuItemClicked,menuObject,"hgTrackUi_follow");
+                                     return true; }
+                               };
+                     } else
+                         o[rightClick.makeImgTag("folderWrench.png")+" Configure "+rec.shortLabel +
+                           " track set..."] = {
+                             onclick: function(menuItemClicked, menuObject) {
+                                 rightClick.hit(menuItemClicked, menuObject, "hgTrackUi_follow");
+                                 return true; }
+                           };
+                     if(jQuery.floatMgr) {
+                         o[(rightClick.selectedMenuItem.id == rightClick.floatingMenuItem ?
+                                 selectedImg : blankImg) + " float"] = {
+                             onclick: function(menuItemClicked, menuObject) {
+                                 rightClick.hit(menuItemClicked, menuObject, "float");
+                                 return true; }
+                         };
                      }
-                     o[str] = { onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "hilightMode"); return true; }};
+                     menu.push($.contextMenu.separator);
                      menu.push(o);
                  }
-                 //menu.push({"view image": {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "viewImg"); return true; }}});
-             }
  
-             if(selectedMenuItem && rec) {
-                 // Add cfg options at just shy of end...
-                 // configureBy==none,         subtracks get folder, stand-alones get nothing
-                 // configureBy==clickThrough, subtracks get folder, stand-alones get wrench but it will not be a popup
-                 // configureBy==popup         subtracks get wrench and folder, stand-alones get wrench as popup
+                 // Add view image at end
                  var o = new Object();
-                 if(tdbIsLeaf(rec)) {
-                     if ( rec["configureBy"] != 'none'
-                     &&  (rec["configureBy"] != 'clickThrough' || rec.parentTrack == undefined))
-                         o[makeImgTag("wrench.png") + " Configure " + rec.shortLabel] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "hgTrackUi_popup"); return true; }};
-                     if(rec.parentTrack != undefined)
-                         o[makeImgTag("folderWrench.png") + " Configure " + rec.parentLabel + " track set..."] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "hgTrackUi_follow"); return true; }};
-                 } else if (rec["configureBy"] != 'none')
-                     o[makeImgTag("folderWrench.png") + " Configure " + rec.shortLabel + " track set..."] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "hgTrackUi_follow"); return true; }};
-                 if(jQuery.floatMgr) {
-                     o[(selectedMenuItem.id == floatingMenuItem ? selectedImg : blankImg) + " float"] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "float"); return true; }};
-                 }
+                 o[rightClick.makeImgTag("eye.png") + " View image"] = {
+                     onclick: function(menuItemClicked, menuObject) {
+                         rightClick.hit(menuItemClicked, menuObject, "viewImg");
+                         return true; }
+                 };
                  menu.push($.contextMenu.separator);
                  menu.push(o);
-             }
  
-             // Add view image at end
-             var o = new Object();
-             o[makeImgTag("eye.png") + " View image"] = {onclick: function(menuItemClicked, menuObject) { contextMenuHit(menuItemClicked, menuObject, "viewImg"); return true; }};
-             menu.push($.contextMenu.separator);
-             menu.push(o);
- 
-             return menu;
-         },
-         {
-             beforeShow: function(e) {
-                 // console.log(mapItems[selectedMenuItem]);
-                 selectedMenuItem = findMapItem(e);
-                 // XXXX? blockUseMap = true;
-                 return true;
+                 return menu;
              },
-             hideTransition:'hide', // hideCallback fails if these are not defined.
-             hideSpeed:10,
-             hideCallback: function() {
-                 $('p.btn.blueButtons').removeClass('blueButtons');
-                 $('tr.trDraggable.greenRows').removeClass('greenRows');
-             }
-         });
-     return;
- }
- 
- function parseMap(ele, reset)
- {
- // Parse the jQuery <map> object into returned mapItems array (ele needn't be the element attached to current document).
-         if(reset || !mapItems) {
-             mapItems = new Array();
-         }
-         if(ele) {
-                 var i = mapItems.length;
-                 // src is necessary under msie
-                 var src = ele.next().attr('src');
-                 ele.children().each(function() {
-                     if (this.coords != undefined) {
-                         mapItems[i++] = {
-                             r : new Rectangle(this.coords),
-                             href : this.href,
-                             title : this.title,
-                             id : this.id,
-                             src : src,
-                             obj : this
-                         };
-                     }
-                 });
+             {
+                 beforeShow: function(e) {
+                     // console.log(mapItems[rightClick.selectedMenuItem]);
+                     rightClick.selectedMenuItem = rightClick.findMapItem(e);
+                     // XXXX? posting.blockUseMap = true;
+                     return true;
+                 },
+                 hideTransition:'hide', // hideCallback fails if these are not defined.
+                 hideSpeed:10,
+                 hideCallback: function() {
+                     $('p.btn.blueButtons').removeClass('blueButtons');
+                     $('tr.trDraggable.greenRows').removeClass('greenRows');
+                 }
+             });
+         return;
      }
-     return mapItems;
- }
  
- function updateTrackImg(trackName,extraData,loadingId)
- {
-     var data = "hgt.trackImgOnly=1&hgsid=" + getHgsid() + "&hgt.trackNameFilter=" + trackName;
-     if(extraData != undefined && extraData != "")
-         data += "&" + extraData;
-     if(loadingId == undefined || loadingId == "")
-         loadingId = showLoadingImage("tr_" + trackName);
-     $.ajax({
-                 type: "GET",
-                 url: "../cgi-bin/hgTracks",
-                 data: data,
-                 dataType: "html",
-                 trueSuccess: handleUpdateTrackMap,
-                 success: catchErrorOrDispatch,
-                 error: errorHandler,
-                 cmd: 'refresh',
-                 loadingId: loadingId,
-                 id: trackName,
-                 cache: false
-             });
  }
  
- var popUpTrackName = "";
- var popUpTrackDescriptionOnly = false;
- var popSaveAllVars = null;
- 
- function popUpBoxCleanup()
- {  // Clean out the popup box on close
-     if ($('#hgTrackUiDialog').html().length > 0 ) {
-         $('#hgTrackUiDialog').html("");  // clear out html after close to prevent problems caused by duplicate html elements
-         popUpTrackName = ""; //set to defaults
-         popUpTrackDescriptionOnly = false;
-         popSaveAllVars = null;
-     }
- }
+   //////////////////////////////////
+  //// popup (aka modal dialog) ////
+ //////////////////////////////////
+ var popUp = {
  
- function _hgTrackUiPopUp(trackName,descriptionOnly)
- { // popup cfg dialog
-     popUpTrackName = trackName;
-     var myLink = "../cgi-bin/hgTrackUi?g=" + trackName + "&hgsid=" + getHgsid() + "&db=" + getDb();
-     popUpTrackDescriptionOnly = descriptionOnly;
-     if(popUpTrackDescriptionOnly)
-         myLink += "&descriptionOnly=1";
- 
-     var rec = hgTracks.trackDb[trackName];
-     if(!descriptionOnly && rec != null && rec["configureBy"] != null) {
-         if (rec["configureBy"] == 'none')
-             return;
-         else if (rec["configureBy"] == 'clickThrough') {
-             jQuery('body').css('cursor', 'wait');
-             window.location = myLink;
-             return;
-         }  // default falls through to configureBy popup
-     }
-     myLink += "&ajax=1";
-     $.ajax({
-                 type: "GET",
-                 url: myLink,
-                 dataType: "html",
-                 trueSuccess: handleTrackUi,
-                 success: catchErrorOrDispatch,
-                 error: errorHandler,
-                 cmd: selectedMenuItem,
-                 cache: false
-             });
- }
+     trackName:            "",
+     trackDescriptionOnly: false,
+     saveAllVars:          null,
  
- function hgTrackUiPopUp(trackName,descriptionOnly)
- {
-     waitOnFunction( _hgTrackUiPopUp, trackName, descriptionOnly );  // Launches the popup but shields the ajax with a waitOnFunction
- }
+     cleanup: function ()
+     {  // Clean out the popup box on close
+         if ($('#hgTrackUiDialog').html().length > 0 ) {
+             $('#hgTrackUiDialog').html("");  // clear out html after close to prevent problems caused by duplicate html elements
+             popUp.trackName = ""; //set to defaults
+             popUp.trackDescriptionOnly = false;
+             popUp.saveAllVars = null;
+         }
+     },
  
- function hgTrackUiPopCfgOk(popObj, trackName)
- { // When hgTrackUi Cfg popup closes with ok, then update cart and refresh parts of page
-     var rec = hgTracks.trackDb[trackName];
-     var subtrack = tdbIsSubtrack(rec) ? trackName :undefined;  // If subtrack then vis rules differ
-     var allVars = getAllVars($('#pop'), subtrack );
-     var changedVars = varHashChanges(allVars,popSaveAllVars);
-     //warn("cfgVars:"+varHashToQueryString(changedVars));
-     var newVis = changedVars[trackName];
-     var hide = (newVis != null && (newVis == 'hide' || newVis == '[]'));  // subtracks do not have "hide", thus '[]'
-     if($('#imgTbl') == undefined) { // On findTracks or config page
-         setVarsFromHash(changedVars);
-         //if(hide) // TODO: When findTracks or config page has cfg popup, then vis change needs to be handled in page here
-     }
-     else {  // On image page
-         if(hide) {
+     _uiDialigRequest: function (trackName,descriptionOnly)
+     { // popup cfg dialog
+         popUp.trackName = trackName;
+         var myLink = "../cgi-bin/hgTrackUi?g=" + trackName + "&hgsid=" + getHgsid() +
+                      "&db=" + getDb();
+         popUp.trackDescriptionOnly = descriptionOnly;
+         if(popUp.trackDescriptionOnly)
+             myLink += "&descriptionOnly=1";
+ 
+         var rec = hgTracks.trackDb[trackName];
+         if (!descriptionOnly && rec != null && rec["configureBy"] != null) {
+             if (rec["configureBy"] == 'none')
+                 return;
+             else if (rec["configureBy"] == 'clickThrough') {
+                 jQuery('body').css('cursor', 'wait');
+                 window.location = myLink;
+                 return;
+             }  // default falls through to configureBy popup
+         }
+         myLink += "&ajax=1";
+         $.ajax({
+                     type: "GET",
+                     url: myLink,
+                     dataType: "html",
+                     trueSuccess: popUp.uiDialog,
+                     success: catchErrorOrDispatch,
+                     error: errorHandler,
+                     cmd: rightClick.selectedMenuItem,
+                     cache: false
+                 });
+     },
+ 
+     hgTrackUi: function (trackName,descriptionOnly)
+     {
+         waitOnFunction( popUp._uiDialigRequest, trackName, descriptionOnly );  // Launches the popup but shields the ajax with a waitOnFunction
+     },
+ 
+     uiDialogOk: function (popObj, trackName)
+     {   // When hgTrackUi Cfg popup closes with ok, then update cart and refresh parts of page
+         var rec = hgTracks.trackDb[trackName];
+         var subtrack = tdbIsSubtrack(rec) ? trackName :undefined;  // If subtrack then vis rules differ
+         var allVars = getAllVars($('#pop'), subtrack );
+         var changedVars = varHashChanges(allVars,popUp.saveAllVars);
+         //warn("cfgVars:"+varHashToQueryString(changedVars));
+         var newVis = changedVars[trackName];
+         var hide = (newVis != null && (newVis == 'hide' || newVis == '[]'));  // subtracks do not have "hide", thus '[]'
+         if($('#imgTbl') == undefined) { // On findTracks or config page
              setVarsFromHash(changedVars);
-             $('#tr_' + trackName).remove();
-             initImgTblButtons();
-             loadImgAreaSelect(false);
-         } else {
-             // Keep local state in sync if user changed visibility
-             if(newVis != null) {
-                 updateVisibility(trackName, newVis);
-             }
-             var urlData = varHashToQueryString(changedVars);
-             if(urlData.length > 0) {
-                 if(mapIsUpdateable) {
-                     updateTrackImg(trackName,urlData,"");
-                 } else {
-                     window.location = "../cgi-bin/hgTracks?" + urlData + "&hgsid=" + getHgsid();
+             //if(hide) // TODO: When findTracks or config page has cfg popup, then vis change needs to be handled in page here
+         }
+         else {  // On image page
+             if(hide) {
+                 setVarsFromHash(changedVars);
+                 $('#tr_' + trackName).remove();
+                 dragReorder.init();
+                 dragSelect.load(false);
+             } else {
+                 // Keep local state in sync if user changed visibility
+                 if(newVis != null) {
+                     vis.update(trackName, newVis);
+                 }
+                 var urlData = varHashToQueryString(changedVars);
+                 if(urlData.length > 0) {
+                     if(imageV2.mapIsUpdateable) {
+                         imageV2.requestImgUpdate(trackName,urlData,"");
+                     } else {
+                         window.location = "../cgi-bin/hgTracks?" + urlData +
+                                           "&hgsid=" + getHgsid();
+                     }
                  }
              }
          }
+     },
+ 
+     uiDialog: function (response, status)
+     {
+     // Take html from hgTrackUi and put it up as a modal dialog.
+ 
+         // make sure all links (e.g. help links) open up in a new window
+         response = response.replace(/<a /ig, "<a target='_blank' ");
+ 
+         // TODO: Shlurp up any javascript files from the response and load them with $.getScript()
+         // example <script type='text/javascript' SRC='../js/tdreszer/jquery.contextmenu-1296177766.js'></script>
+         var cleanHtml = response;
+         var shlurpPattern=/\<script type=\'text\/javascript\' SRC\=\'.*\'\>\<\/script\>/gi;
+         var jsFiles = cleanHtml.match(shlurpPattern);
+         cleanHtml = cleanHtml.replace(shlurpPattern,"");
+         shlurpPattern=/\<script type=\'text\/javascript\'>.*\<\/script\>/gi;
+         var jsEmbeded = cleanHtml.match(shlurpPattern);
+         cleanHtml = cleanHtml.replace(shlurpPattern,"");
+         //<LINK rel='STYLESHEET' href='../style/ui.dropdownchecklist-1276528376.css' TYPE='text/css' />
+         shlurpPattern=/\<LINK rel=\'STYLESHEET\' href\=\'.*\' TYPE=\'text\/css\' \/\>/gi;
+         var cssFiles = cleanHtml.match(shlurpPattern);
+         cleanHtml = cleanHtml.replace(shlurpPattern,"");
+ 
+         $('#hgTrackUiDialog').html("<div id='pop' style='font-size:.9em;'>"+ cleanHtml +"</div>");
+ 
+         // Strategy for poups with js:
+         // - jsFiles and CSS should not be included in html.  Here they are shluped out.
+         // - The resulting files ought to be loadable dynamically (with getScript()), but this was not working nicely with the modal dialog
+         //   Therefore include files must be included with hgTracks CGI !
+         // - embedded js should not be in the popup box.
+         // - Somethings should be in a popup.ready() function, and this is emulated below, as soon as the cleanHtml is added
+         //   Since there are many possible popup cfg dialogs, the ready should be all inclusive.
+ 
+         /* //in open ?  Will load of css work this way?
+         $(cssFiles).each(function (i) {
+             bix = "<LINK rel='STYLESHEET' href='".length;
+             eix = this.lastIndexOf("' TYPE='text/css' />");
+             file = this.substring(bix,eix);
+             $.getScript(file); // Should protect against already loaded files.
+         }); */
+         /* //in open ?  Loads fine, but then dialog gets confused
+         $(jsFiles).each(function (i) {
+             bix = "<script type='text/javascript' SRC='".length;
+             eix = this.lastIndexOf("'></script>");
+             file = this.substring(bix,eix);
+             //$.getScript(file,function(data) { warn(data.substring(0,20) + " loaded")});
+         });*/
+ 
+         if ( ! popUp.trackDescriptionOnly ) {
+             var subtrack = tdbIsSubtrack(hgTracks.trackDb[popUp.trackName]) ? popUp.trackName :"";  // If subtrack then vis rules differ
+             popUp.saveAllVars = getAllVars( $('#hgTrackUiDialog'), subtrack );  // Saves the vars that may get changed by the popup cfg.
+ 
+             // -- popup.ready() -- Here is the place to do things that might otherwise go into a $('#pop').ready() routine!
+         }
+ 
+         // Searching for some selblance of size suitability
+         var popMaxHeight = ($(window).height() - 40);
+         var popMaxWidth  = ($(window).width() - 40);
+         var popWidth     = 740;
+         if (popWidth > popMaxWidth)
+             popWidth > popMaxWidth;
+ 
+         $('#hgTrackUiDialog').dialog({
+                                 ajaxOptions: {
+                                     // This doesn't work
+                                     cache: true
+                                 },
+                                 resizable: true,
+                                 height: (popUp.trackDescriptionOnly ? popMaxHeight : 'auto'), // Let description scroll vertically
+                                 width: popWidth,
+                                 minHeight: 200,
+                                 minWidth: 700,
+                                 maxHeight: popMaxHeight,
+                                 maxWidth: popMaxWidth,
+                                 modal: true,
+                                 closeOnEscape: true,
+                                 autoOpen: false,
+                                 buttons: { "OK": function() {
+                                         if ( ! popUp.trackDescriptionOnly )
+                                             popUp.uiDialogOk($('#pop'), popUp.trackName);
+                                         $(this).dialog("close");
+                                 }},
+                                 // popup.ready() doesn't seem to work in open.  So there is no need for open at this time.
+                                 //open: function() {
+                                 //     var subtrack = tdbIsSubtrack(hgTracks.trackDb[popUp.trackName]) ? popUp.trackName :"";  // If subtrack then vis rules differ
+                                 //     popUp.saveAllVars = getAllVars( $('#pop'), subtrack );
+                                 //},
+                                 open: function () {
+                                     if ( ! popUp.trackDescriptionOnly ) {
+                                         $('#hgTrackUiDialog').find('.filterBy,.filterComp').each(
+                                             function(i) {
+                                                 if ($(this).hasClass('filterComp'))
+                                                     ddcl.setup(this);
+                                                 else
+                                                     ddcl.setup(this, 'noneIsAll');
+                                             }
+                                         );
+                                     }
+                                 },
+                                 close: function() {
+                                     popUp.cleanup();
+                                 }
+                             });
+         // FIXME: Why are open and close no longer working!!!
+         if(popUp.trackDescriptionOnly) {
+             var myWidth =  $(window).width() - 300;
+             if(myWidth > 900)
+                 myWidth = 900;
+             $('#hgTrackUiDialog').dialog("option", "maxWidth", myWidth);
+             $('#hgTrackUiDialog').dialog("option", "width", myWidth);
+             $('#hgTrackUiDialog').dialog('option' , 'title' ,
+                                hgTracks.trackDb[popUp.trackName].shortLabel+" Track Description");
+             $('#hgTrackUiDialog').dialog('open');
+             var buttOk = $('button.ui-state-default');
+             if($(buttOk).length == 1)
+                 $(buttOk).focus();
+         } else {
+             $('#hgTrackUiDialog').dialog('option' , 'title' ,
+                                   hgTracks.trackDb[popUp.trackName].shortLabel+" Track Settings");
+             $('#hgTrackUiDialog').dialog('open');
+         }
      }
  }
  
- function handleTrackUi(response, status)
- {
- // Take html from hgTrackUi and put it up as a modal dialog.
- 
-     // make sure all links (e.g. help links) open up in a new window
-     response = response.replace(/<a /ig, "<a target='_blank' ");
- 
-     // TODO: Shlurp up any javascript files from the response and load them with $.getScript()
-     // example <script type='text/javascript' SRC='../js/tdreszer/jquery.contextmenu-1296177766.js'></script>
-     var cleanHtml = response;
-     cleanHtml = stripJsFiles(cleanHtml,   false);   // true means show error msg
-     cleanHtml = stripCssFiles(cleanHtml,  false);
-     cleanHtml = stripJsEmbedded(cleanHtml,false);// NOTE: embeded warnBox msgs will be put into the warnbox
+   ///////////////////////////////
+  //// imageV2  (aka imgTbl) ////
+ ///////////////////////////////
+ var imageV2 = {
  
-     $('#hgTrackUiDialog').html("<div id='pop' style='font-size:.9em;'>" + cleanHtml + "</div>");
+     enabled:        false,    // Will be set to true unless advancedJavascriptFeatures is turned off OR if track search of config page
+     imgTbl:         null,     // formerly "trackImgTbl"  The imgTbl or null if non-imageV2.
+     inPlaceUpdate:  false,    // modified based on value of hgTracks.inPlaceUpdate and mapIsUpdateable
+     mapIsUpdateable:true,
+     lastTrack:      null,     // formerly (lastMapItem) this is used to try to keep what the last track the cursor passed.
  
-     // Strategy for poups with js:
-     // - jsFiles and CSS should not be included in html.  Here they are shluped out.
-     // - The resulting files ought to be loadable dynamically (with getScript()), but this was not working nicely with the modal dialog
-     //   Therefore include files must be included with hgTracks CGI !
-     // - embedded js should not be in the popup box.
-     // - Somethings should be in a popup.ready() function, and this is emulated below, as soon as the cleanHtml is added
-     //   Since there are many possible popup cfg dialogs, the ready should be all inclusive.
+     markAsDirtyPage: function ()
+     {   // Page is marked as dirty so that the backbutton can be overridden
+         var dirty = $('#dirty');
+         if (dirty != undefined && dirty.length != 0)
+             $(dirty).val('true');
+     },
  
-     if( ! popUpTrackDescriptionOnly ) {
-         var subtrack = tdbIsSubtrack(hgTracks.trackDb[popUpTrackName]) ? popUpTrackName :"";  // If subtrack then vis rules differ
-         popSaveAllVars = getAllVars( $('#hgTrackUiDialog'), subtrack );  // Saves the vars that may get changed by the popup cfg.
+     isDirtyPage: function ()
+     { // returns true if page was marked as dirty
+     // This will allow the backbutton to be overridden
  
-         // -- popup.ready() -- Here is the place to do things that might otherwise go into a $('#pop').ready() routine!
-     }
- 
-     // Searching for some selblance of size suitability
-     var popMaxHeight = ($(window).height() - 40);
-     var popMaxWidth  = ($(window).width() - 40);
-     var popWidth     = 740;
-     if (popWidth > popMaxWidth)
-         popWidth > popMaxWidth;
- 
-     $('#hgTrackUiDialog').dialog({
-                                ajaxOptions: {
-                                    // This doesn't work
-                                    cache: true
-                                },
-                                resizable: true,
-                                height: (popUpTrackDescriptionOnly ? popMaxHeight : 'auto'), // Let description scroll vertically
-                                width: popWidth,
-                                minHeight: 200,
-                                minWidth: 700,
-                                maxHeight: popMaxHeight,
-                                maxWidth: popMaxWidth,
-                                modal: true,
-                                closeOnEscape: true,
-                                autoOpen: false,
-                                buttons: { "OK": function() {
-                                     if( ! popUpTrackDescriptionOnly )
-                                         hgTrackUiPopCfgOk($('#pop'), popUpTrackName);
-                                     $(this).dialog("close");
-                                }},
-                                // popup.ready() doesn't seem to work in open.  So there is no need for open at this time.
-                                //open: function() {
-                                //     var subtrack = tdbIsSubtrack(hgTracks.trackDb[popUpTrackName]) ? popUpTrackName :"";  // If subtrack then vis rules differ
-                                //     popSaveAllVars = getAllVars( $('#pop'), subtrack );
-                                //},
-                                open: function () {
-                                     if( ! popUpTrackDescriptionOnly ) {
-                                         $('#hgTrackUiDialog').find('.filterBy,.filterComp').each( function(i) {
-                                             if ($(this).hasClass('filterComp'))
-                                                 ddcl.setup(this);
-                                             else
-                                                 ddcl.setup(this, 'noneIsAll');
-                                         });
-                                     }
-                                },
-                                close: function() {
-                                    popUpBoxCleanup();
-                                }
-                            });
-     // FIXME: Why are open and close no longer working!!!
-     if(popUpTrackDescriptionOnly) {
-         var myWidth =  $(window).width() - 300;
-         if(myWidth > 900)
-             myWidth = 900;
-         $('#hgTrackUiDialog').dialog("option", "maxWidth", myWidth);
-         $('#hgTrackUiDialog').dialog("option", "width", myWidth);
-         $('#hgTrackUiDialog').dialog('option' , 'title' , hgTracks.trackDb[popUpTrackName].shortLabel + " Track Description");
-         $('#hgTrackUiDialog').dialog('open');
-         var buttOk = $('button.ui-state-default');
-         if($(buttOk).length == 1)
-             $(buttOk).focus();
-     } else {
-         $('#hgTrackUiDialog').dialog('option' , 'title' , hgTracks.trackDb[popUpTrackName].shortLabel + " Track Settings");
-         $('#hgTrackUiDialog').dialog('open');
-     }
- }
- 
- function afterImgTblReload()
- {
- // Reload various UI widgets after updating imgTbl map.
-     parseMap(null, true);
-     $("map[name!=ideoMap]").each( function(t) { parseMap($(this, false));});
-     initImgTblButtons();
-     loadImgAreaSelect(false);
-     // Do NOT reload context menu (otherwise we get the "context menu sticks" problem).
-     // loadContextMenu($('#tr_' + id));
-     if(trackImgTbl.tableDnDUpdate)
-         trackImgTbl.tableDnDUpdate();
-     reloadFloatingItem();
-     // Turn on drag scrolling.
-     if(hgTracks.imgBoxPortal) {
-         $("div.scroller").panImages();
-     }
-     loadRemoteTracks();
-     markAsDirtyPage();
- }
+         var dirty = $('#dirty');
+         if (dirty != undefined && dirty.length > 0) {
+             if ($(dirty).val() == 'true')
+                 return true;
+         }
+         return false;
+     },
+ 
+     updateTiming: function (response)
+     {   // update measureTiming text on current page based on what's in the response
+         var reg = new RegExp("(<span class='timing'>.+?</span>)", "g");
+         var strs = [];
+         for(var a = reg.exec(response); a != null && a[1] != null; a = reg.exec(response)) {
+             strs.push(a[1]);
+         }
+         if(strs.length > 0) {
+             $('.timing').remove();
+             for(var i = strs.length; i > 0; i--) {
+                 $('body').prepend(strs[i - 1]);
+             }
+         }
+         reg = new RegExp("(<span class='trackTiming'>[\\S\\s]+?</span>)");
+         a = reg.exec(response);
+         if(a != null && a[1] != null) {
+             $('.trackTiming').replaceWith(a[1]);
+         }
+     },
+ 
+     afterReload: function ()
+     {   // Reload various UI widgets after updating imgTbl map.
+         dragReorder.init();
+         dragSelect.load(false);
+         // Do NOT reload context menu (otherwise we get the "context menu sticks" problem).
+         // rightClick.load($('#tr_' + id));
+         if(imageV2.imgTbl.tableDnDUpdate)
+             imageV2.imgTbl.tableDnDUpdate();
+         rightClick.reloadFloatingItem();
+         // Turn on drag scrolling.
+         if(hgTracks.imgBoxPortal) {
+             $("div.scroller").panImages();
+         }
+         imageV2.loadRemoteTracks();
+         imageV2.markAsDirtyPage();
+     },
  
- function updateTrackImgForId(html, id)
- {
- // update row in imgTbl for given id.
- // return true if we successfully pull slice for id and update it in imgTrack.
-     var str = "<TR id='tr_" + id + "'[^>]*>([\\s\\S]+?)</TR>";
-     var reg = new RegExp(str);
-     var a = reg.exec(html);
-     if(a && a[1]) {
-         var tr = $('#tr_' + id);
-         $(tr).html(a[1]);
-         // NOTE: Want to examine the png? Uncomment:
-         //var img = $('#tr_' + id).find("img[id^='img_data_']").attr('src');
-         //warn("Just parsed image:<BR>"+img);
- 
-         // >1x dragScrolling needs some extra care.
-         if(hgTracks.imgBoxPortal && (hgTracks.imgBoxWidth > hgTracks.imgBoxPortalWidth)) {
-             if (hgTracks.imgBoxPortalLeft != undefined) {
-                 $(tr).find('.panImg').css({'left': hgTracks.imgBoxPortalLeft });
-                 $(tr).find('.tdData').css( {'backgroundPosition': hgTracks.imgBoxPortalLeft } );
+     updateImgForId: function (html, id)
+     {   // update row in imgTbl for given id.
+         // return true if we successfully pull slice for id and update it in imgTrack.
+         var str = "<TR id='tr_" + id + "'[^>]*>([\\s\\S]+?)</TR>";
+         var reg = new RegExp(str);
+         var a = reg.exec(html);
+         if(a && a[1]) {
+             var tr = $('#tr_' + id);
+             if (tr.length > 0) {
+                 $(tr).html(a[1]);
+                 // NOTE: Want to examine the png? Uncomment:
+                 //var img = $('#tr_' + id).find("img[id^='img_data_']").attr('src');
+                 //warn("Just parsed image:<BR>"+img);
+ 
+                 // >1x dragScrolling needs some extra care.
+                 if(hgTracks.imgBoxPortal && (hgTracks.imgBoxWidth > hgTracks.imgBoxPortalWidth)) {
+                     if (hgTracks.imgBoxPortalLeft != undefined) {
+                         $(tr).find('.panImg').css({'left': hgTracks.imgBoxPortalLeft });
+                         $(tr).find('.tdData').css(
+                                 {'backgroundPosition': hgTracks.imgBoxPortalLeft});
+                     }
+                 }
+                 return true;
              }
          }
-         return true;
-     } else {
          return false;
-     }
- }
+     },
  
- function updateTiming(response)
- {
- // update measureTiming text on current page based on what's in the response
-     var reg = new RegExp("(<span class='timing'>.+?</span>)", "g");
-     var strs = [];
-     for(var a = reg.exec(response); a != null && a[1] != null; a = reg.exec(response)) {
-         strs.push(a[1]);
-     }
-     if(strs.length > 0) {
-         $('.timing').remove();
-         for(var i = strs.length; i > 0; i--) {
-             $('body').prepend(strs[i - 1]);
-         }
-     }
-     reg = new RegExp("(<span class='trackTiming'>[\\S\\s]+?</span>)");
-     a = reg.exec(response);
-     if(a != null && a[1] != null) {
-         $('.trackTiming').replaceWith(a[1]);
-     }
- }
+     requestImgUpdate: function (trackName,extraData,loadingId)
+     {
+         var data = "hgt.trackImgOnly=1&hgsid=" + getHgsid() + "&hgt.trackNameFilter=" + trackName;
+         if(extraData != undefined && extraData != "")
+             data += "&" + extraData;
+         if(loadingId == undefined || loadingId == "")
+             loadingId = showLoadingImage("tr_" + trackName);
+         var getOrPost = "GET";
+         if ((data.length) > 2000) // extraData could contain a bunch of changes from the cfg dialog
+             getOrPost = "POST";
+         $.ajax({
+                     type: getOrPost,
+                     url: "../cgi-bin/hgTracks",
+                     data: data,
+                     dataType: "html",
+                     trueSuccess: imageV2.updateImgAndMap,
+                     success: catchErrorOrDispatch,
+                     error: errorHandler,
+                     cmd: 'refresh',
+                     loadingId: loadingId,
+                     id: trackName,
+                     cache: false
+                 });
+     },
  
- function handleUpdateTrackMap(response, status)
- {
- // Handle ajax response with an updated trackMap image, map and optional ideogram.
- //
- // this.cmd can be used to figure out which menu item triggered this.
- // this.id == appropriate track if we are retrieving just a single track.
- 
-     // update local hgTracks.trackDb to reflect possible side-effects of ajax request.
-     var json = scrapeVariable(response, "hgTracks");
-     var oldTrackDb = hgTracks.trackDb;
-     if(json == undefined) {
-         showWarning("hgTracks object is missing from the response");
-     } else {
-         if(this.id != null) {
-             if(json.trackDb[this.id]) {
-                 var visibility = visibilityStrsOrder[json.trackDb[this.id].visibility];
-                 var limitedVis;
-                 if(json.trackDb[this.id].limitedVis)
-                     limitedVis = visibilityStrsOrder[json.trackDb[this.id].limitedVis];
-                 if(this.newVisibility && limitedVis && this.newVisibility != limitedVis)
-                     // see redmine 1333#note-9
-                     alert("There are too many items to display the track in " + this.newVisibility + " mode.");
-                 var rec = hgTracks.trackDb[this.id];
-                 rec.limitedVis = json.trackDb[this.id].limitedVis;
-                 updateVisibility(this.id, visibility);
+     updateImgAndMap: function (response, status)
+     {   // Handle ajax response with an updated trackMap image, map and optional ideogram.
+         //
+         // this.cmd can be used to figure out which menu item triggered this.
+         // this.id == appropriate track if we are retrieving just a single track.
+ 
+         // update local hgTracks.trackDb to reflect possible side-effects of ajax request.
+         var json = scrapeVariable(response, "hgTracks");
+         var oldTrackDb = hgTracks.trackDb;
+         if(json == undefined) {
+             showWarning("hgTracks object is missing from the response");
+         } else {
+             if(this.id != null) {
+                 if(json.trackDb[this.id]) {
+                     var visibility = vis.enumOrder[json.trackDb[this.id].visibility];
+                     var limitedVis;
+                     if(json.trackDb[this.id].limitedVis)
+                         limitedVis = vis.enumOrder[json.trackDb[this.id].limitedVis];
+                     if(this.newVisibility && limitedVis && this.newVisibility != limitedVis)
+                         // see redmine 1333#note-9
+                         alert("There are too many items to display the track in " +
+                                 this.newVisibility + " mode.");
+                     var rec = hgTracks.trackDb[this.id];
+                     rec.limitedVis = json.trackDb[this.id].limitedVis;
+                     vis.update(this.id, visibility);
+                 } else {
+                     showWarning("Invalid hgTracks.trackDb received from the server");
+                 }
              } else {
-                 showWarning("Invalid hgTracks.trackDb received from the server");
+                 hgTracks.trackDb = json.trackDb;
              }
-         } else {
-             hgTracks.trackDb = json.trackDb;
          }
-     }
-     if(imageV2 && this.id && this.cmd && this.cmd != 'wholeImage' && this.cmd != 'selectWholeGene') {
-           // Extract <TR id='tr_ID'>...</TR> and update appropriate row in imgTbl;
-           // this updates src in img_left_ID, img_center_ID and img_data_ID and map in map_data_ID
-           var id = this.id;
-           if(updateTrackImgForId(response, id)) {
-                afterImgTblReload();
-           } else {
-                showWarning("Couldn't parse out new image for id: " + id);
-                //alert("Couldn't parse out new image for id: " + id+"BR"+response);  // Very helpful
-           }
-     } else {
-         if(imageV2) {
-             // Implement in-place updating of hgTracks image
-             setPositionByCoordinates(json.chromName, json.winStart + 1, json.winEnd);
-             $("input[name='c']").val(json.chromName);
-             $("input[name='l']").val(json.winStart);
-             $("input[name='r']").val(json.winEnd);
-             if(json.cgiVersion != hgTracks.cgiVersion) {
-                 // Must reload whole page because of a new version on the server; this should happen very rarely.
-                 // Note that we have already updated position based on the user's action.
-                 jQuery('body').css('cursor', 'wait');
- 	        document.TrackHeaderForm.submit();
+         if(imageV2.enabled
+         && this.id
+         && this.cmd
+         && this.cmd != 'wholeImage'
+         && this.cmd != 'selectWholeGene') {
+             // Extract <TR id='tr_ID'>...</TR> and update appropriate row in imgTbl;
+             // this updates src in img_left_ID, img_center_ID and img_data_ID and map in map_data_ID
+             var id = this.id;
+             if(imageV2.updateImgForId(response, id)) {
+                 imageV2.afterReload();
              } else {
-                 // We update rows one at a time (updating the whole imgTable at one time doesn't work in IE).
-                 for (var id in hgTracks.trackDb) {
-                     if(hgTracks.trackDb[id].type != "remote" && !updateTrackImgForId(response, id)) {
-                         showWarning("Couldn't parse out new image for id: " + id);
-                         //alert("Couldn't parse out new image for id: " + id+"BR"+response);  // Very helpful
+                 showWarning("Couldn't parse out new image for id: " + id);
+                 //alert("Couldn't parse out new image for id: " + id+"BR"+response);  // Very helpful
+             }
+         } else {
+             if(imageV2.enabled) {
+                 // Implement in-place updating of hgTracks image
+                 genomePos.setByCoordinates(json.chromName, json.winStart + 1, json.winEnd);
+                 $("input[name='c']").val(json.chromName);
+                 $("input[name='l']").val(json.winStart);
+                 $("input[name='r']").val(json.winEnd);
+                 if(json.cgiVersion != hgTracks.cgiVersion) {
+                     // Must reload whole page because of a new version on the server; this should happen very rarely.
+                     // Note that we have already updated position based on the user's action.
+                     jQuery('body').css('cursor', 'wait');
+                     document.TrackHeaderForm.submit();
+                 } else {
+                     // We update rows one at a time (b/c updating the whole imgTable at one time doesn't work in IE).
+                     for (var id in hgTracks.trackDb) {
+                     // handle case where invisible items may be in the trackDb list (see redmine #5670).
+                         if(hgTracks.trackDb[id].type != "remote"
+                         && hgTracks.trackDb[id].visibility > 0 // && $('#tr_' + id).length > 0
+                         && !imageV2.updateImgForId(response, id)) {
+                             showWarning("Couldn't parse out new image for id: " + id);
+                         }
                      }
+                 /* This (disabled) code handles dynamic addition of tracks:
+                     for (var id in hgTracks.trackDb) {
+                         if(oldTrackDb[id] == undefined) {
+                             // XXXX Tim, what s/d abbr attribute be?
+                             $('#imgTbl').append("<tr id='tr_" + id + "' class='imgOrd trDraggable'></tr>");
+                             imageV2.updateImgForId(response, id);
+                             vis.update(id, vis.enumOrder[hgTracks.trackDb[id].visibility]);
+                         }
+                     }
+                 */
+                     hgTracks = json;
+                     genomePos.original = undefined;
+                     initVars();
+                     imageV2.afterReload();
                  }
- /* This (disabled) code handles dynamic addition of tracks:
-                 for (var id in hgTracks.trackDb) {
-                     if(oldTrackDb[id] == undefined) {
-                         // XXXX Tim, what s/d abbr attribute be?
-                         $('#imgTbl').append("<tr id='tr_" + id + "' class='imgOrd trDraggable'></tr>");
-                         updateTrackImgForId(response, id);
-                         updateVisibility(id, visibilityStrsOrder[hgTracks.trackDb[id].visibility]);
+             } else {
+                 warn("ASSERT: Attempt to update track without advanced javascript features.");
+             }
+             // now pull out and parse the map.
+             //a = /<MAP id='map' Name=map>([\s\S]+)<\/MAP>/.exec(response);
+             //if(!a[1])
+             //    showWarning("Couldn't parse out map");
+         }
+         // Parse out new ideoGram url (if available)
+         // e.g.: <IMG SRC = "../trash/hgtIdeo/hgtIdeo_hgwdev_larrym_61d1_8b4a80.gif" BORDER=1 WIDTH=1039 HEIGHT=21 USEMAP=#ideoMap id='chrom'>
+         // We do this last b/c it's least important.
+         var a = /<IMG([^>]+SRC[^>]+id='chrom'[^>]*)>/.exec(response);
+         if(a && a[1]) {
+             b = /SRC\s*=\s*"([^")]+)"/.exec(a[1]);
+             if(b[1]) {
+                 $('#chrom').attr('src', b[1]);
+             }
+         }
+         if(hgTracks.measureTiming) {
+             imageV2.updateTiming(response);
+         }
+         if(this.disabledEle) {
+             this.disabledEle.attr('disabled', '');
+         }
+         if(this.loadingId) {
+             hideLoadingImage(this.loadingId);
+         }
+         jQuery('body').css('cursor', '');
+         if(this.currentId) {
+             var top = $("#tr_" + this.currentId).position().top;
+             $(window).scrollTop(top - this.currentIdYOffset);
+         }
+     },
+ 
+     loadRemoteTracks: function ()
+     {
+         if(typeof(hgTracks.trackDb) != "undefined" && hgTracks.trackDb != null) {
+             for (var id in hgTracks.trackDb) {
+                 var rec = hgTracks.trackDb[id];
+                 if(rec.type == "remote") {
+                     if($("#img_data_" + id).length > 0) {
+                         // load the remote track renderer via jsonp
+                         rec.loadingId = showLoadingImage("tr_" + id);
+                         var script = document.createElement('script');
+                         var pos = parsePosition(genomePos.get());
+                         var name = rec.remoteTrack || id;
+                         script.setAttribute('src',
+                                 rec.url + "?track=" + name +
+                                 "&jsonp=imageV2.remoteTrackCallback&position=" +
+                                 encodeURIComponent(pos.chrom + ":" + pos.start + "-" + pos.end) +
+                                 "&pix=" + $('#imgTbl').width()
+                         );
+                         document.getElementsByTagName('head')[0].appendChild(script);
                      }
                  }
- */
-                 hgTracks = json;
-                 originalPosition = undefined;
-                 initVars();
-                 afterImgTblReload();
              }
+         }
+     },
+ 
+     remoteTrackCallback: function (rec)
+     // jsonp callback to load a remote track.
+     {
+         if(rec.error) {
+             alert("retrieval from remote site failed with error: " + rec.error)
          } else {
-             a= /<IMG([^>]+SRC[^>]+id='trackMap[^>]*)>/.exec(response);
-             // Deal with a is null
-             if(a[1]) {
-                     var b = /WIDTH\s*=\s*['"]?(\d+)['"]?/.exec(a[1]);
-                     var width = b[1];
-                     b = /HEIGHT\s*=\s*['"]?(\d+)['"]?/.exec(a[1]);
-                     var height = b[1];
-                     b = /SRC\s*=\s*"([^")]+)"/.exec(a[1]);
-                     var src = b[1];
-                     $('#trackMap').attr('src', src);
-                     var obj = imgAreaSelect.data('imgAreaSelect');
-                     if(width) {
-                         trackImg.attr('width', width);
+             var remoteTrack = rec.track;
+             for (var track in hgTracks.trackDb) {
+                 if(hgTracks.trackDb[track].remoteTrack == remoteTrack) {
+                     $('#img_data_' + track).attr('style', "left:-116px; top: -23px;");
+                     $('#img_data_' + track).attr('height', rec.height);
+                     // XXXX use width in some way?
+            //       $('#img_data_' + track).attr('width', rec.width);
+                     $('#img_data_' + track).attr('width', $('#img_data_ruler').width());
+                     $('#img_data_' + track).attr('src', rec.img);
+                     $('#td_data_' + track + ' > div').each(function(index) {
+                         if(index == 1) {
+                             var style = $(this).attr('style');
+                             style = style.replace(/height:\s*\d+/i, "height:" + rec.height);
+                             $(this).attr('style', style);
+                         }
+                     });
+                     var style = $('#p_btn_' + track).attr('style');
+                     style = style.replace(/height:\s*\d+/i, "height:" + rec.height);
+                     $('#p_btn_' + track).attr('style', style);
+                     if(hgTracks.trackDb[track].loadingId) {
+                         hideLoadingImage(hgTracks.trackDb[track].loadingId);
                      }
-                     if(height) {
-                         trackImg.attr('height', height);
- 
-                         // obj.setOptions({minHeight : height, maxHeight: height});
-                         // obj.getOptions().minHeight = height;
-         		// obj.getOptions().maxHeight = height;
-                         // XXX doesn't work obj.options.maxHeight = height;
-                         // This doesn't work: obj.windowResize();
-                         // This works, but causes weird error IF we also change minHeight and maxHeight.
-                         // jQuery(window).triggerHandler("resize");
- 
-                        // After much debugging, I found the best way to have imgAreaSelect continue to work
-                        // was to reload it:
-                        loadImgAreaSelect(false);
-                        // XXX this doesn't work (i.e. does't make the re-sized row draggable under safari).
-                        trackImgTbl.tableDnD();
-                    }
-             } else {
-                 showWarning("Couldn't parse out new image");
+                 }
              }
          }
-         // now pull out and parse the map.
-         a = /<MAP id='map' Name=map>([\s\S]+)<\/MAP>/.exec(response);
-         if(a[1]) {
-             var $map = $('<map>' + a[1] + '</map>');
-             parseMap($map, true);
+     },
+ 
+     navigateButtonClick: function (ele) // called from hgTracks.c
+     {   // code to update just the imgTbl in response to navigation buttons (zoom-out etc.).
+         // This is currently experimental code (controlled by IN_PLACE_UPDATE in imageV2.h).
+         if(imageV2.inPlaceUpdate) {
+             var params = ele.name + "=" + ele.value;
+             $(ele).attr('disabled', 'disabled');
+             // dinking navigation needs additional data
+             if(ele.name == "hgt.dinkLL" || ele.name == "hgt.dinkLR") {
+                 params += "&dinkL=" + $("input[name='dinkL']").val();
+             } else if(ele.name == "hgt.dinkRL" || ele.name == "hgt.dinkRR") {
+                 params += "&dinkR=" + $("input[name='dinkR']").val();
+             }
+             imageV2.navigateInPlace(params, $(ele), false);
+             return false;
          } else {
-             showWarning("Couldn't parse out map");
+             return true;
          }
-     }
-     // Parse out new ideoGram url (if available)
-     // e.g.: <IMG SRC = "../trash/hgtIdeo/hgtIdeo_hgwdev_larrym_61d1_8b4a80.gif" BORDER=1 WIDTH=1039 HEIGHT=21 USEMAP=#ideoMap id='chrom'>
-     // We do this last b/c it's least important.
-     var a = /<IMG([^>]+SRC[^>]+id='chrom'[^>]*)>/.exec(response);
-     if(a && a[1]) {
-         b = /SRC\s*=\s*"([^")]+)"/.exec(a[1]);
-         if(b[1]) {
-             $('#chrom').attr('src', b[1]);
+     },
+ 
+     updateButtonClick: function (ele) // UNUSED?
+     {   // code to update the imgTbl based on changes in the track controls.
+         // This is currently experimental code and is dead in the main branch.
+         if(imageV2.mapIsUpdateable) {
+             var data = "";
+             $("select").each(function(index, o) {
+                 var cmd = $(this).val();
+                 if(cmd == "hide") {
+                     if(hgTracks.trackDb[this.name] != undefined) {
+                         alert("Need to implement hide");
+                     }
+                 } else {
+                     if(hgTracks.trackDb[this.name] == undefined
+                     || cmd != vis.enumOrder[hgTracks.trackDb[this.name].visibility]) {
+                         if(data.length > 0) {
+                             data = data + "&";
+                         }
+                         data = data + this.name + "=" + cmd;
+                     }
+             }
+             });
+             if(data.length > 0) {
+                 imageV2.navigateInPlace(data, null, false);
+             }
+             return false;
+         } else {
+             return true;
          }
-     }
-     if(hgTracks.measureTiming) {
-         updateTiming(response);
-     }
-     if(this.disabledEle) {
-         this.disabledEle.attr('disabled', '');
-     }
-     if(this.loadingId) {
-         hideLoadingImage(this.loadingId);
-     }
-     jQuery('body').css('cursor', '');
-     if(this.currentId) {
-         var top = $("#tr_" + this.currentId).position().top;
-         $(window).scrollTop(top - this.currentIdYOffset);
-     }
- }
+     },
+ 
+     jumpButtonOnClick: function () // called from hgTracks.c
+     {   // onClick handler for the "jump" button.
+         // Handles situation where user types a gene name into the gene box and immediately hits the jump button,
+         // expecting the browser to jump to that gene.
+         var gene = $('#suggest').val();
+         var db = getDb();
+         if(gene
+         && gene.length > 0
+         && gene != "gene"
+         && db
+         && (genomePos.getOriginalPos() == genomePos.get() || genomePos.get().length == 0)) {
+             pos = lookupGene(db, gene);
+             if(pos) {
+                 genomePos.set(pos, null);
+             } else {
+                 // turn this into a full text search.
+                 genomePos.set(gene, null);
+             }
+         }
+         return true;
+     },
  
- function handleViewImg(response, status)
- { // handles view image response, which must get new image without imageV2 gimmickery
-     jQuery('body').css('cursor', '');
-     var str = "<IMG[^>]*SRC='([^']+)'";
-     var reg = new RegExp(str);
-     a = reg.exec(response);
-     if(a && a[1]) {
-         if(window.open(a[1]) == null) {
-             windowOpenFailedMsg();
+     navigateInPlace: function (params, disabledEle, keepCurrentTrackVisible)
+     {
+     // request an hgTracks image, using params
+     // disabledEle is optional; this element will be enabled when update is complete
+     // If keepCurrentTrackVisible is true, we try to maintain relative position of the item under the mouse after the in-place update.
+         jQuery('body').css('cursor', '');
+         var currentId, currentIdYOffset;
+         if(keepCurrentTrackVisible) {
+             var item = rightClick.currentMapItem || imageV2.lastTrack;
+             if(item) {
+                 var top = $("#tr_" + item.id).position().top;
+                 if(top >= $(window).scrollTop()
+                 || top < $(window).scrollTop() + $(window).height()) {
+                     // don't bother if the item is not currently visible.
+                     currentId = item.id;
+                     currentIdYOffset = top - $(window).scrollTop();
+                 }
+             }
          }
-         return;
+         $.ajax({
+                 type: "GET",
+                 url: "../cgi-bin/hgTracks",
+                 data: params + "&hgt.trackImgOnly=1&hgt.ideogramToo=1&hgsid=" + getHgsid(),
+                 dataType: "html",
+                 trueSuccess: imageV2.updateImgAndMap,
+                 success: catchErrorOrDispatch,
+                 error: errorHandler,
+                 cmd: 'wholeImage',
+                 loadingId: showLoadingImage("imgTbl"),
+                 disabledEle: disabledEle,
+                 currentId: currentId,
+                 currentIdYOffset: currentIdYOffset,
+                 cache: false
+             });
      }
-     showWarning("Couldn't parse out img src");
+ 
  }
  
- function jumpButtonOnClick()
- {
- // onClick handler for the "jump" button.
- // Handles situation where user types a gene name into the gene box and immediately hits the jump button,
- // expecting the browser to jump to that gene.
-     var gene = $('#suggest').val();
-     var db = getDb();
-     if(gene && gene != "gene" && db && gene.length > 0 && (getOriginalPosition() == getPosition() || getPosition().length == 0)) {
-         pos = lookupGene(db, gene);
-         if(pos) {
-             setPosition(pos, null);
-         } else {
-             // turn this into a full text search.
-             setPosition(gene, null);
+   ////////////////////////////////////
+  //// suggest  (aka gene search) ////
+ ////////////////////////////////////
+ var suggestBox = {
+ 
+     init: function (db)
+     {
+         if(jQuery.fn.autocomplete && $('input#suggest') && db) {
+             if(jQuery.fn.Watermark) {
+                 $('#suggest').Watermark("gene");
+             }
+             $('input#suggest').autocomplete({
+                 delay: 500,
+                 minLength: 2,
+                 source: ajaxGet(function () {return getDb();}, new Object, true),
+                 open: function(event, ui) {
+                     var pos = $(this).offset().top + $(this).height();
+                     if (!isNaN(pos)) {
+                         var maxHeight = $(window).height() - pos - 30;  // take off a little more because IE needs it
+                         var auto = $('.ui-autocomplete');
+                         var curHeight = $(auto).children().length * 21;
+                         if (curHeight > maxHeight)
+                             $(auto).css({maxHeight: maxHeight+'px',overflow:'scroll'});
+                         else
+                             $(auto).css({maxHeight: 'none',overflow:'hidden'});
+                     }
+                 },
+                 select: function (event, ui) {
+                         genomePos.set(ui.item.id, commify(getSizeFromCoordinates(ui.item.id)));
+                         vis.makeTrackVisible($("#suggestTrack").val());
+                         // jQuery('body').css('cursor', 'wait');
+                         // document.TrackHeaderForm.submit();
+                     }
+             });
+ 
+             // I want to set focus to the suggest element, but unforunately that prevents PgUp/PgDn from
+             // working, which is a major annoyance.
+             // $('input#suggest').focus();
          }
      }
-     return true;
  }
  
- function remoteTrackCallback(rec)
- // jsonp callback to load a remote track.
- {
-     if(rec.error) {
-         alert("retrieval from remote site failed with error: " + rec.error)
-     } else {
-         var remoteTrack = rec.track;
-         for (var track in hgTracks.trackDb) {
-             if(hgTracks.trackDb[track].remoteTrack == remoteTrack) {
-                 $('#img_data_' + track).attr('style', "left:-116px; top: -23px;");
-                 $('#img_data_' + track).attr('height', rec.height);
-                 // XXXX use width in some way?
- //        $('#img_data_' + track).attr('width', rec.width);
-                 $('#img_data_' + track).attr('width', $('#img_data_ruler').width());
-                 $('#img_data_' + track).attr('src', rec.img);
-                 $('#td_data_' + track + ' > div').each(function(index) {
-                                                            if(index == 1) {
-                                                                var style = $(this).attr('style');
-                                                                style = style.replace(/height:\s*\d+/i, "height:" + rec.height);
-                                                                $(this).attr('style', style);
-                                                            }
-                                                        });
-                 var style = $('#p_btn_' + track).attr('style');
-                 style = style.replace(/height:\s*\d+/i, "height:" + rec.height);
-                 $('#p_btn_' + track).attr('style', style);
-                 if(hgTracks.trackDb[track].loadingId) {
-                     hideLoadingImage(hgTracks.trackDb[track].loadingId);
-                 }
+   //////////////////////
+  //// track search ////
+ //////////////////////
+ var trackSearch = {
+ 
+     searchKeydown: function (event)
+     {
+         if (event.which == 13) {
+             // Required to fix problem on IE and Safari where value of hgt_tSearch is "-" (i.e. not "Search").
+             $("input[name=hgt_tsPage]").val(0);  // NOTE: must match TRACK_SEARCH_PAGER in hg/inc/searchTracks.h
+             $('#trackSearch').submit();
+             // This doesn't work with IE or Safari.
+             // $('#searchSubmit').click();
+         }
+     },
+ 
+     init: function ()
+     {
+         // Track search uses tabs
+         if($("#tabs").length > 0) {
+             // Search page specific code
+ 
+             var val = $('#currentTab').val();
+             $("#tabs").tabs({
+                                 show: function(event, ui) {
+                                     $('#currentTab').val(ui.panel.id);
+                                 },
+                                 select: function(event, ui) { findTracksSwitchTabs(ui); }
+                             });
+             $('#tabs').show();
+             $("#tabs").tabs('option', 'selected', '#' + val);
+             if(val =='simpleTab' && $('div#found').length < 1) {
+                 $('input#simpleSearch').focus();
              }
+             $("#tabs").css('font-family', jQuery('body').css('font-family'));
+             $("#tabs").css('font-size', jQuery('body').css('font-size'));
+             $('.submitOnEnter').keydown(trackSearch.searchKeydown);
+             findTracksNormalize();
+             updateMetaDataHelpLinks(0);
          }
      }
  }
  
- function searchKeydown(event)
- {
-     if (event.which == 13) {
-         // Required to fix problem on IE and Safari where value of hgt_tSearch is "-" (i.e. not "Search").
-         $("input[name=hgt_tsPage]").val(0);  // NOTE: must match TRACK_SEARCH_PAGER in hg/inc/searchTracks.h
-         $('#trackSearch').submit();
-         // This doesn't work with IE or Safari.
-         // $('#searchSubmit').click();
-     }
- }
  
- function windowOpenFailedMsg()
- {
-     alert("Your web browser prevented us from opening a new window.\n\nPlease change your browser settings to allow pop-up windows from " + document.domain + ".");
- }
+ /*
+ 
+ // wait for jStore to prepare the storage engine (this token reload code is experimental and currently dead).
+ jQuery.jStore && jQuery.jStore.ready(function(engine) {
+     // alert(engine.jri);
+     // wait for the storage engine to be ready.
+     engine.ready(function(){
+         var engine = this;
+         var newToken = hgTracks.time;
+         if(newToken) {
+             var oldToken = engine.get("token");
+             if(oldToken && oldToken == newToken) {
+                 // user has hit the back button.
+                 jQuery('body').css('cursor', 'wait');
+                 window.location = "../cgi-bin/hgTracks?hgsid=" + getHgsid();
+             }
+         }
+         engine.set("token", newToken);
+     });
+ });
+ 
+ */
  
- function updateVisibility(track, visibility)
+   ///////////////
+  //// READY ////
+ ///////////////
+ $(document).ready(function()
  {
- // Updates visibility state in hgTracks.trackDb and any visible elements on the page.
- // returns true if we modify at least one select in the group list
-     var rec = hgTracks.trackDb[track];
-     var selectUpdated = false;
-     $("select[name=" + track + "]").each(function(t) {
-                                           $(this).attr('class', visibility == 'hide' ? 'hiddenText' : 'normalText');
-                                           $(this).val(visibility);
-                                           selectUpdated = true;
-                                       });
-     if(rec) {
-         rec.localVisibility = visibility;
+     // The page may be reached via browser history (back button)
+     // If so, then this code should detect if the image has been changed via js/ajax
+     // and will reload the image if necessary.
+     // NOTE: this is needed for IE but other browsers can detect the dirty page much earlier
+     if (imageV2.isDirtyPage()) {
+         // mark as non dirty to avoid infinite loop in chrome.
+         $('#dirty').val('false');
+         jQuery('body').css('cursor', 'wait');
+             window.location = "../cgi-bin/hgTracks?hgsid=" + getHgsid();
+             return false;
      }
-     return selectUpdated;
- }
+     initVars();
  
- function getVisibility(track)
- {
- // return current visibility for given track
-     var rec = hgTracks.trackDb[track];
-     if(rec) {
-         if(rec.localVisibility) {
-             return rec.localVisibility;
-         } else {
-             return visibilityStrsOrder[rec.visibility];
+     var db = getDb();
+     suggestBox.init(db);
+ 
+     if(jQuery.jStore) {
+         // Experimental code to handle "user hits back button" problem by reloading the page based on the user's cart
+         if(jQuery.browser.msie && jQuery.browser.version < 8) {
+             // IE 7 requires flash to support jStore.
+             jQuery.extend(jQuery.jStore.defaults, {
+                               project: 'hgTracks',
+                               engine: 'flash',
+                               flash: '/jStore.Flash.html'
+                           });
          }
-     } else {
-         return null;
+         jQuery.jStore.load();
      }
- }
  
- function makeSureSuggestTrackIsVisible()
- {
- // make sure to show knownGene/refGene track is in at least pack (redmine #3484).
-     var track = $("#suggestTrack").val();
-     if(track != null && getVisibility(track) != "full") {
-         updateVisibility(track, 'pack');
-         $("<input type='hidden' name='" + track + "'value='pack'>").appendTo($(document.TrackHeaderForm));
-     }
- }
  
- function reloadFloatingItem()
- {
- // currently dead (experimental code)
-     if(floatingMenuItem) {
-         $('#img_data_' + floatingMenuItem).parent().makeFloat({x:"current",y:"current", speed: 'fast', alwaysVisible: true, alwaysTop: true});
+     // Convert map AREA gets to post the form, ensuring that cart variables are kept up to date (but turn this off for search form).
+     if($("FORM").length > 0 && $('#trackSearch').length == 0) {
+         var allLinks = $('a');
+         $( allLinks ).unbind('click');
+         $( allLinks ).click( posting.saveSettings );
      }
- }
- 
- function handleZoomCodon(response, status)
- {
-     var json = eval("(" + response + ")");
-     if(json.pos) {
-         setPosition(json.pos, 3);
-         if(document.TrackForm)
-             document.TrackForm.submit();
-         else
-             document.TrackHeaderForm.submit();
-     } else {
-         alert(json.error);
+     if($('#pdfLink').length == 1) {
+         $('#pdfLink').click(function(i) {
+             var thisForm=$('#TrackForm');
+             if(thisForm != undefined && $(thisForm).length == 1) {
+                 //alert("posting form:"+$(thisForm).attr('name'));
+                 updateOrMakeNamedVariable($(thisForm),'hgt.psOutput','on');
+                 return postTheForm($(thisForm).attr('name'),this.href);
+             }
+             return true;
+         });
      }
- }
  
- function navigateButtonClick(ele)
- {
- // code to update just the imgTbl in response to navigation buttons (zoom-out etc.).
- // This is currently experimental code (controlled by IN_PLACE_UPDATE in imageV2.h).
-     if(inPlaceUpdate) {
-         var params = ele.name + "=" + ele.value;
-         $(ele).attr('disabled', 'disabled');
-         // dinking navigation needs additional data
-         if(ele.name == "hgt.dinkLL" || ele.name == "hgt.dinkLR") {
-             params += "&dinkL=" + $("input[name='dinkL']").val();
-         } else if(ele.name == "hgt.dinkRL" || ele.name == "hgt.dinkRR") {
-             params += "&dinkR=" + $("input[name='dinkR']").val();
-         }
-         navigateInPlace(params, $(ele), false);
-         return false;
-     } else {
-         return true;
-     }
- }
+     if(imageV2.enabled) {
  
- function navigateInPlace(params, disabledEle, keepCurrentTrackVisible)
- {
- // request an hgTracks image, using params
- // disabledEle is optional; this element will be enabled when update is complete
- // If keepCurrentTrackVisible is true, we try to maintain relative position of the item under the mouse after the in-place update.
-     jQuery('body').css('cursor', '');
-     var currentId, currentIdYOffset;
-     if(keepCurrentTrackVisible) {
-         var item = currentMapItem || lastMapItem;
-         if(item) {
-             var top = $("#tr_" + item.id).position().top;
-             if(top >= $(window).scrollTop() || top < $(window).scrollTop() + $(window).height()) {
-                 // don't bother if the item is not currently visible.
-                 currentId = item.id;
-                 currentIdYOffset = top - $(window).scrollTop();
-             }
+         // Make imgTbl allow drag reorder of imgTrack rows
+         dragReorder.init();
+         var imgTable = $(".tableWithDragAndDrop");
+         if($(imgTable).length > 0) {
+             $(imgTable).tableDnD({
+                 onDragClass: "trDrag",
+                 dragHandle: "dragHandle",
+                 scrollAmount: 40,
+                 onDragStart: function(ev, table, row) {
+                     mouse.saveOffset(ev);
+                     $(document).bind('mousemove',posting.blockTheMapOnMouseMove);
+ 
+                     // Can drag a contiguous set of rows if dragging blue button
+                     table.tableDnDConfig.dragObjects = [ row ]; // defaults to just the one
+                     var btn = $( row ).find('p.btnBlue');  // btnBlue means cursor over left button
+                     if (btn.length == 1) {
+                         table.tableDnDConfig.dragObjects = dragReorder.getContiguousRowSet(row);
+                         var compositeSet = dragReorder.getCompositeSet(row);
+                         if (compositeSet && compositeSet.length > 0)
+                             $( compositeSet ).find('p.btn').addClass('blueButtons');  // blue persists
+                     }
+                 },
+                 onDrop: function(table, row, dragStartIndex) {
+                     var compositeSet = dragReorder.getCompositeSet(row);
+                     if (compositeSet && compositeSet.length > 0)
+                         $( compositeSet ).find('p.btn').removeClass('blueButtons');  // blue persists
+                     if($(row).attr('rowIndex') != dragStartIndex) {
+                         // NOTE Even if dragging a contiguous set of rows,
+                         // still only need to check the one under the cursor.
+                         if(dragReorder.setOrder) {
+                             dragReorder.setOrder(table);
+                         }
+                         dragReorder.zipButtons( table );
+                     }
+                     $(document).unbind('mousemove',posting.blockTheMapOnMouseMove);
+                     setTimeout('posting.allowMapClicks();',50); // Necessary incase the onDrop was over a map item. onDrop takes precedence.
+                 }
+             });
          }
+ 
+         // Drag scroll init
+         if(hgTracks.imgBoxPortal) {
+             // Turn on drag scrolling.
+             $("div.scroller").panImages();
+         }
+         //$("#zoomSlider").slider({ min: -4, max: 3, step: 1 });//, handle: '.ui-slider-handle' });
+ 
+         // Retrieve tracks via AJAX that may take too long to draw initialliy (i.e. a remote bigWig)
+         var retrievables = $('#imgTbl').find("tr.mustRetrieve")
+         if($(retrievables).length > 0) {
+             $(retrievables).each( function (i) {
+                 var trackName = $(this).attr('id').substring(3);
+                 imageV2.requestImgUpdate(trackName,"","");
+             });
+         }
+         imageV2.loadRemoteTracks();
      }
-     $.ajax({
-                type: "GET",
-                url: "../cgi-bin/hgTracks",
-                data: params + "&hgt.trackImgOnly=1&hgt.ideogramToo=1&hgsid=" + getHgsid(),
-                dataType: "html",
-                trueSuccess: handleUpdateTrackMap,
-                success: catchErrorOrDispatch,
-                error: errorHandler,
-                cmd: 'wholeImage',
-                loadingId: showLoadingImage("imgTbl"),
-                disabledEle: disabledEle,
-                currentId: currentId,
-                currentIdYOffset: currentIdYOffset,
-                cache: false
-            });
- }
  
- function updateButtonClick(ele)
- {
- // code to update the imgTbl based on changes in the track controls.
- // This is currently experimental code and is dead in the main branch.
-     if(mapIsUpdateable) {
-         var data = "";
-         $("select").each(function(index, o) {
-                                                var cmd = $(this).val();
-                                                if(cmd == "hide") {
-                                                      if(hgTracks.trackDb[this.name] != undefined) {
-                                                          alert("Need to implement hide");
-                                                      }
-                                                } else {
-                                                      if(hgTracks.trackDb[this.name] == undefined || cmd != visibilityStrsOrder[hgTracks.trackDb[this.name].visibility]) {
-                                                         if(data.length > 0) {
-                                                              data = data + "&";
-                                                         }
-                                                         data = data + this.name + "=" + cmd;
-                                                      }
-                                                }
-                                             });
-         if(data.length > 0) {
-             navigateInPlace(data, null, false);
+     // Drag select in chromIdeogram
+     if($('img#chrom').length == 1) {
+         if($('area.cytoBand').length > 1) {
+             $('img#chrom').chromDrag();
          }
-         return false;
-     } else {
-         return true;
      }
- }
  
- function handleChangePosition(response, status)
- {
-     var json = eval("(" + response + ")");
-     setPosition(json.pos);
- }
+     // Track search uses tabs
+     trackSearch.init();
  
- function changeAssemblies(ele)
- {
- // code to update page when user changes assembly select list.
-     $.ajax({
-                type: "GET",
-                url: "../cgi-bin/hgApi",
-                data: "cmd=defaultPos&db=" + getDb(),
-                dataType: "html",
-                trueSuccess: handleChangePosition,
-                success: catchErrorOrDispatch,
-                error: errorHandler,
-                cache: true
-            });
-     return false;
- }
+     // Drag select initialize
+     if (imageV2.enabled) {   // moved from window.load().
+         dragSelect.load(true);
+ 
+         if($('#hgTrackUiDialog'))
+             $('#hgTrackUiDialog').hide();
+ 
+         // Don't load contextMenu if jquery.contextmenu.js hasn't been loaded
+         if (jQuery.fn.contextMenu) {
+             rightClick.load(imageV2.imgTbl);
+         }
+     }
 -});
++});