/* the following is the configuration for the built in default values,
   it is advised to change these from the calling html, but if avoided
   there they can be set here.
*/

var rootName = 'a²';
var rootPath='./';   /* the absolute URL on the server for the path
                       which is browsable
                     */
var rootItems=undefined;  /* can be overridden with an array of strings
                             indicating the files available at the root */
var rootDirs=undefined;   /* can be overridden with an array of directories
                             containing apache listings to be screenscraped
                             for URLS */
var enableThumbs=false;

/** end of configuration **/

var items = new Array;
var dirs  = new Array;
var current = -1;
var sinc = 0;
var slide_delay = 10;
var secs_left = 0;

var imageTop = 0;
var imageLeft = 0;
var imageWidth = 0;
var imageHeight = 0;
var imageZoom = 0;
var isFit = false;

var navWidth = 0;
var navHeight = 0;

var isSliding = false;
var isFullscreen = false;

function titleFile(file)
{
  return file.replace(/\.html$/,"");
}

function $(id)
{
  return document.getElementById(id);
}

var infoupdater = undefined;

function updateImageInfo()
{
  var win = $('window');
  var img = $('image');

  if (img==undefined)
    {
      clearInterval(infoupdater);
      infoupdater = undefined;
      return;
    }

  /*img.style.maxWidth = "100%";*/
  imageWidth = img.clientWidth;
  imageHeight = img.clientHeight;

  if (imageWidth > 0 &&
      imageWidth > 28)   /* IE6/7 reports the size of the loading icon (which is 28px)*/
    {
      clearInterval(infoupdater);
      infoupdater = undefined;
      if (imageWidth > $('window').clientWidth ||
          imageHeight > $('window').clientHeight ||
          isFit)
        {
          zoomFit();
        }
      else
        {
          imageZoom=1.0;
          centerView();
        }
    }
}

function setZoom(zoom)
{
  var win = $('window');
  var avail_width = win.clientWidth;
  var avail_height = win.clientHeight;
  var img = $('image');
    
  var dx, dy;
 
  if (imageZoom == 0.0)
    imageZoom = 1.0;

  imageLeft += avail_width*0.5
  imageTop += avail_height*0.5

  imageLeft *= (zoom/imageZoom);
  imageTop *= (zoom/imageZoom);

  imageZoom = zoom;

  imageLeft -= avail_width*0.5
  imageTop -= avail_height*0.5

  img.style.width = (imageWidth * imageZoom) + "px";
  img.style.height = (imageHeight * imageZoom) + "px";
  img.style.left = (-imageLeft)+"px";
  img.style.top = (-imageTop)+"px";

  resizeView();
  isFit = false;
  updateControlState();
  updateNavigator();
}

function ieversion()
{
  var version=0
  if (navigator.appVersion.indexOf("MSIE")!=-1)
  {
    temp=navigator.appVersion.split("MSIE")
    version=parseFloat(temp[1])
  }
  return version;
}

function ancientIE()
{
  return (ieversion()>0.0 && ieversion()<7.0)
}

function updateNavigator()
{
  var win = $('window');
  var nav = $('navigator');
  var navRect = $('navigatorRectangle');
  if (!win || !nav || !navRect)
    return;
  
  var avail_width = win.clientWidth;
  var avail_height = win.clientHeight;

  if (imageWidth * imageZoom > avail_width ||
      imageHeight * imageZoom > avail_height)
    {
      var height = ((256*imageHeight)/imageWidth);;
      var width = ((256*imageWidth)/imageHeight);;

      if (width>height)
        {
           width = 256;
        }
      else
        {
           height = 256;
        }
      navWidth = width;
      navHeight = height;

      var zoom = navWidth/(imageWidth*imageZoom);

      nav.src = items[current];
      nav.style.height = navHeight + "px";
      nav.style.width = navWidth + "px";
      nav.style.left = (viewportWidth()-navWidth) + "px";
      nav.style.top = (viewportHeight()-navHeight) + "px";
      nav.style.cursor = 'crosshair';
      navRect.style.cursor = 'crosshair';

      navRect.style.height = (avail_height * zoom) + "px";
      navRect.style.width = (avail_width * zoom) + "px";
      navRect.style.left = (imageLeft * zoom +  viewportWidth()-navWidth) + "px";
      navRect.style.top = (imageTop * zoom + viewportHeight()-navHeight) + "px";


      nav.style.display = "block";
      navRect.style.display = "block";
    }
  else
    {
      $('navigator').style.display = "none";
      $('navigatorRectangle').style.display = "none";
    }
}

function navmousedown (event)
{
  var id = 'navigator'
  var el;
  var x, y;
  if (lock)
    return;
  lock = true;
  drag.element = $(id);
  x = event.clientX;
  y = event.clientY;
  drag.previousX = x;
  drag.previousY = y;

  if (document.addEventListener)
  {
      document.addEventListener("mousemove", navmousemove, true);
      document.addEventListener("mouseup",   navmouseup, true);
      event.preventDefault();
  }
  else if (document.attachEvent)
    {
      document.attachEvent("onmousemove", navmousemove);
      document.attachEvent("onmouseup",   navmouseup);
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
  return navmousemove (event);
}


function navmousemove(event)
{
  var x, y;
  var dx, dy;
  x = event.clientX;
  y = event.clientY;
  dx = x - drag.previousX;
  dy = y - drag.previousY;
  drag.previousX = x;
  drag.previousY = y;
  
  /* do stuff with dx/dy */

  x -= (viewportWidth()-navWidth);
  y -= (viewportHeight()-navHeight);

  imageLeft = ((x) * (imageWidth*imageZoom)/navWidth) - $('window').clientWidth/2;
  imageTop = ((y) * (imageHeight*imageZoom)/navHeight) - $('window').clientHeight/2;

  $('image').style.top = (-imageTop) + "px";
  $('image').style.left =  (-imageLeft) + "px";
  updateNavigator();

  if (event.preventDefault)
  {
    event.preventDefault();
  }
  else
  {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
  }
}

function navmouseup(event)
{
  if (document.removeEventListener)
  {
      document.removeEventListener("mousemove", navmousemove, true);
      document.removeEventListener("mouseup", navmouseup, true);
  }
  else
   {
      document.detachEvent("onmousemove", navmousemove);
      document.detachEvent("onmouseup", navmouseup);
    }
  lock = false;
}


function centerView()
{
  var win = $('window');
  var img = $('image');
  imageLeft = -(win.clientWidth - imageWidth*imageZoom)/2;
  imageTop = -(win.clientHeight - imageHeight*imageZoom)/2;
  img.style.left = (-imageLeft)+"px";
  img.style.top = (-imageTop)+"px";
}

function zoomFit()
{
  var win = $('window');
  var img = $('image');
  var avail_width = win.clientWidth;
  var avail_height = win.clientHeight;
  var zoomW = avail_width/imageWidth;
  var zoomH = avail_height/imageHeight;
  var zoom = zoomH;
  
  if (zoomW<zoomH)
    zoom=zoomW;

  setZoom (zoom);
  imageLeft = 0;
  imageTop = 0;
  img.style.left = (-imageLeft)+"px";
  img.style.top = (-imageTop)+"px";
  isFit = true;
  centerView();
  updateControlState();
}

function zoomNormal()
{
  setZoom(1.0);
}

function zoomIn()
{
  setZoom(imageZoom * 1.4);
}
function zoomOut()
{
  setZoom(imageZoom * 0.6);
}

function viewportHeight()
{
  var viewportheight;

  if (window.innerHeight)
   {
     viewportheight = window.innerHeight
   }
  else if (document.documentElement && 
           document.documentElement.clientHeight &&
           document.documentElement.clientHeight != 0)
   {
     viewportheight = document.documentElement.clientHeight
   }
  return viewportheight;
}


function viewportWidth()
{
  var viewportwidth;

  if (window.innerWidth)
   {
     viewportwidth = window.innerWidth
   }
  else if (document.documentElement && 
           document.documentElement.clientWidth &&
           document.documentElement.clientWidth != 0)
   {
     viewportwidth = document.documentElement.clientWidth
   }
  return viewportwidth;
}

var prevfoo = 0;
var prevbar = 0;

function resizeView()
{
  var content = $('content');
  var win = $('window');
  if (!win)
    return;

  var foo = viewportHeight() - win.offsetTop;
  var bar = viewportWidth() - win.offsetLeft;

  if (rootName == 'codecave.org')
   {
      if (!(foo > 0 && foo < 8000))
        {
         if (!(foo < 0)) { }
         {   /* avoid doing anything if we're scrolled off start */
             alert("height computation failed" + foo );
         }
        }  
      else
        {
          win.style.height = (foo-3) + "px";
          win.style.width = (bar-4) + "px";
          //$('page').style.width = bar + 'px';
          //$('directory').style.height = foo + "px";
        }
   }
  else
   {
     win.style.height = content.clientHeight + "px";
     win.style.width = content.clientWidth+ "px";
   }
  if (isFullscreen)
    {
       win.style.height = foo + "px";
       win.style.width = bar + "px";
    }

  if (!(foo==prevfoo && bar==prevbar))
    {
       prevfoo = foo;
       prevbar = bar;
       zoomFit ();
    }

}

function loadFile(no)
{
  var URL = items[no];
  var a = URL.split('/');
  var file = a[a.length-1];

  document.title=rootName + "/" + URL.replace();

  $('location').innerHTML = crumbs(URL) +"<a class='crumb' href='"+URL+"' style='text-decoration:none'>"+ titleFile(file) +"</a>";
  window.location.hash=URL;
  URL=rootPath + URL;
  a = URL.split('/');

  if (infoupdater==undefined)
    infoupdater=setInterval(updateImageInfo, 100);

  list=$('directory');
  a= list.getElementsByTagName('li');
  for (var i=0;i<a.length;i++)
    {
       if(i==no+dirs.length)/*a[i].innerHTML==file)*/
         {
           a[i].className = 'selected';
         }
       else
         {
           a[i].className = '';
         }
    }

  var extension = URL.match(/\..*$/);
  if (extension)
    {
      extension = (""+extension).replace(/.*\./,"");
    }

  $('content').innerHTML = "<div id='frame'>...</div>";

  //$('full').className = 'inactive';
  $('slide').className = 'inactive';
  $('zoomin').className = 'inactive';
  $('zoomout').className = 'inactive';
  $('zoomfit').className = 'inactive';
  $('zoomnormal').className = 'inactive';
  $('next').className = 'inactive';
  $('prev').className = 'inactive';

  if (extension == 'gz')
   {
     $('frame').innerHTML = "<p>This file is a .gz file (perhaps even a .tar.gz) file, there is nothing I can do for this file, you probably better download it then you can do something with it there.</p><a href='"+URL+"'>download "+URL+"</a>";
   }
  else if (extension == 'svg')
   {
     $('frame').innerHTML = "<object type='image/svg+xml' data='"+URL+"' width='100%' style='height:30em'>browser does not render SVG</object>";
   }
  else if (extension == 'ogv' ||
           extension == 'ogg')
   {
     $('frame').innerHTML = "<video src='"+URL+"' width='100%' controls='controls' autoplay=autoplay'>browser does not support the video tag</video>";
   }
  else if (extension == 'jpeg' ||
      extension == 'jpg' ||
      extension == 'JPG' ||
      extension == 'png' ||
      extension == 'PNG' ||
      extension == 'gif')
   {
     $('frame').innerHTML = "<img id='navigator' onmousedown='navmousedown(event);'/><div id='navigatorRectangle' onmousedown='navmousedown(event);'></div><div id='window'><img id='image' src='"+URL+"' onmousedown='drag_start(event)'/></div>";

     resizeView();
     $('navigator').style.top = (viewportHeight()-128) + "px";
     $('navigator').style.left = (viewportWidth()-256) + "px";
     $('navigator').style.position = 'fixed';
     $('navigator').style.width = '256px';
     $('navigator').style.height = '128px';
     $('navigator').style.background = 'gray';
     $('navigator').style.zIndex = 1;
     $('navigatorRectangle').style.zIndex = 2;
     $('navigatorRectangle').style.top = (viewportHeight()-128) + "px";
     $('navigatorRectangle').style.left= (viewportWidth()-256) + "px";
     $('navigatorRectangle').style.position = 'fixed';
     $('navigatorRectangle').style.width = '256px';
     $('navigatorRectangle').style.height = '128px';

     if(ancientIE())
       {
         $('navigator').style.position = 'absolute';
         $('navigatorRectangle').style.position = 'absolute';
       }

     //$('full').className='';
     $('slide').className = '';
     /*
     $('zoomin').className='';
     $('zoomout').className='';
     $('zoomfit').className='';
     $('zoomnormal').className='';
     */
     $('window').style.overflow='hidden';
     $('window').style.cursor='all-scroll';
     $('navigatorRectangle').style.border = '1px solid white';

     imageTop = 0;
     imageLeft = 0;
     $('image').style.position = 'relative';
     $('image').style.top = imageTop + "px";
     $('image').style.left = imageLeft + "px";
     updateNavigator();
     $('window').style.position = 'relative'; /* needed to make it work in IE */
     /*$('frame').innerHTML = "<img style='max-width:100%;width:100%;'  src='"+URL+"'/>";*/
   }
  else if (extension == 'html' ||
           extension == 'htm' ||
           extension == 'xhtml')
   {
     importStatic("frame", URL);
   }
  else if (extension == 'txt' ||
           extension == 'tex' ||
           extension == 'patch' ||
           extension == 'sh' ||
           extension == 'am' ||
           extension == 'in' ||
           extension == 'h' ||
           extension == 'js' ||
           extension == 'json' ||
           extension == 'css' ||
           extension == 'xml' ||
           extension == 'rb' ||
           extension == 'c' ||
           extension == 'cpp' ||
           file == "README" ||
           file == "NEWS" ||
           file == "Makefile" ||
           file == "AUTHORS" ||
           file == "COPYING" ||
           file == "ChangeLog" ||
           file == "INSTALL" ||
           file == "FAQ")
   {
     importPre("frame", URL);
   }
  else if (extension == 'mpg' ||
           extension == 'wmv' ||
           extension == 'avi' ||
           extension == 'mp4')
   {
     $('frame').innerHTML = 
"<embed id='videp' src='" + URL + "' width='640' height='640'> </embed>";


   }

  else if (extension == 'flv' ||
           extension == 'mp4')
   {
     $('frame').innerHTML = 
"<object id='window' type='application/x-shockwave-flash' width='320' height='260' wmode='transparent' data='flvplayer.swf?file="+URL+"'> <param name='movie' value='flvplayer.swf?file="+URL+"'/> <param name='wmode' value='transparent' />";


   }
  else
   {
     $('frame').innerHTML =  

         "<em>hmm:</em> Don't know how to handle '" + extension + 
         "' extension try a direct link instead: " +
         "<a href='" + URL + "'>" + URL + "</a> ";
   }
  current = no;
  $('nextPreview').style.backgroundImage = "url("+items[no+1]+")";
  /*$('prevPreview').style.backgroundImage = "url("+items[no-1]+")";*/
  resizeView();
}


function crumbs(dir)
{
  var els = dir.split('/');
  ret = "<span onclick='loadDir(\"\")'><span style='cursor:pointer;' class='crumb'>"+rootName+"<span class='pathsep'>/</span></span></span>";
  for (var i=0;i<els.length-1;i++)
    { 
      var url = "";
      for (var j=0;j<i+1;j++)
        url += els[j] + "/";

      ret += "<span class='crumb' onclick='loadDir(\""+url+"\")' style='cursor:pointer'>"+ els[i] + "<span class='pathsep'>/</span></span>";
    }
  return ret;
}

var it=0;

var oldloc = "-";

function sanitize()
{
  resizeView();
  updateNavigator();

  /* location has changed... */
  if (window.location.hash != oldloc)
  {
     oldloc = window.location.hash;
     urlquery = window.location.hash;
     if (!urlquery)
       {
         urlquery = "";
       }
      urlquery = urlquery.replace(/^#/,"");
      loadDir(urlquery);
  }
}

function slideSecond()
{
   if (secs_left > 0)
     {
       $('slide').innerHTML= secs_left;
       secs_left--;
     }
   else
     {
       secs_left=slide_delay;
       $('slide').innerHTML= secs_left;
       buttonNext();
     }
  if (isSliding)
    setTimeout(slideSecond, 1*1000);
  else
    {
      $('slide').innerHTML = '‣';
    }
  updateControlState();
  true;
}

function buttonSlide()
{
  if (isSliding)
    {
      $('slide').innerHTML = '‣';
      isSliding=false;
    }
  else
    {
      isSliding=true;
      secs_left=slide_delay;
      slideSecond();
      if (!isFullscreen)
        {
           buttonFull();
        }
    }
  updateControlState();
}

function setState(id, state)
{
  $(id).className=state?'active':'';
}

function updateControlState()
{
  setState('full', isFullscreen);
  setState('slide', isSliding);
  //setState('zoomfit', isFit);
}

function buttonFull()
{
  if (!isFullscreen)
    {
      $('content').style.background = "black";
      $('content').style.color = "white";
      $('content').style.position = "fixed";
      $('content').style.height = "100%";
      $('content').style.top = "0";
      $('content').style.left = "0";
      $('controls').style.position= "fixed";
      $('controls').style.top = "0";
      $('controls').style.right = "0";
      $('controls').style.background = "#444";
      $('controls').style.zIndex= "4";
      $('controls').style.padding = "0.2em";

      isFullscreen=true;
      resizeView();
      zoomFit();
    }
  else
    {
      $('controls').style.position= "static";
      $('controls').style.top = "";
      $('controls').style.left = "";
      $('controls').style.background = "transparent";
      $('controls').style.width = "";
      $('controls').style.padding = "";

      $('content').style.background = "transparent";
      $('content').style.position = "static";
      $('content').style.height = "100%";
      $('content').style.top = "";
      $('content').style.left = "";
      $('content').style.color = "inherit";

      if ($('window'))
        $('window').style.width = "auto";


      isFullscreen=false;
      resizeView();
      if (isFit)
        zoomFit();
    }
  updateControlState();
}

function buttonRandom()
{
   var foo=Math.floor(items.length * Math.random());
   loadFile(foo);
}

function buttonNext()
{

       if (current == items.length-1)
         { 
           var a=items[current].split('/');
           if (parseInt(a[a.length-2])>0)
             {
               var newdir="";
               for (var i=0;i<a.length-2;i++)
                 {
                   newdir += a[i] + "/";
                 }
               
               newdir += (parseInt(a[a.length-2])+2) + "/";
               loadDir(newdir);
               return;
             }
           current = -1; /* wrap around */
         }

   loadFile(current+1);
}

function buttonPrev()
{
   loadFile(current-1);
}

  function add_item(url)
  {
    if (url.match(/\/$/))
      {
        dirs[dirs.length]=url;
      }
    else
      {
        items[items.length]=url;
      }
  }

function thumb(no)
{
  var URL = rootPath + items[no];
  var a = URL.split('/');
  var dir="";
  var file = a[a.length-1];
  for (var i=0;i<a.length-1;i++)
    {
      dir += a[i] + "/";
    }
  dir += '.thumbs/' + file + ".jpg"; 
  return dir;
}

function dirLoaded()
{
  var output = "<ul>";
  for (var i=0;i<dirs.length;i++)
    {
      var basename = dirs[i].split('/');
      if (basename.length == 1) /* special hack for top level, allowing links to
                                 * non managed subsites 
                                 */
      {
        var link = dirs[i];
        basename = basename[basename.length-1];
        if (basename == 'hnb')
            link = 'http://hnb.sourceforge.net/';
        output+= "<li style='cursor:pointer' onclick='window.location=\""+link+"\";'><b>" + basename + "/</b></li>";
      }
      else
      {
        basename = basename[basename.length-2];
        output+= "<li style='cursor:pointer' onclick='loadDir(\""+dirs[i]+"\");'><b>" + basename + "/</b></li>";
      }
    }
  for (var i=0;i<items.length;i++)
    {
      var basename = items[i].split('/');
      basename = basename[basename.length-1];
      if (enableThumbs &&
          (basename.match(/\.jpg$/) ||
           basename.match(/\.png$/) ||
           basename.match(/\.gif$/)))
         {
            output+= "<li onclick='loadFile("+i+");' style=' cursor:pointer;'><img src='"+thumb(i)+"' alt='"+basename+"' title='"+basename+"'/></li>";
         }

      else
         {
      output+= "<li style='cursor:pointer' onclick='loadFile("+i+");' style=''>"+basename+"</li>";
         }
    }
  output+="</ul>";

  $('directory').innerHTML = output;

  for (var i=0;i<items.length;i++)
    {
      var basename = items[i].split('/');
      basename = basename[basename.length-1];
      if (basename == file)
        {
          loadFile(i);
          return;
        }
    }
  buttonNext();
}

var i=0;

function loadDir(dir)
{
  $('location').innerHTML=crumbs(dir);
  var a = dir.split('/');
  dir="";
  file = a[a.length-1];
  for (var i=0;i<a.length-1;i++)
    {
      dir += a[i] + "/";
    }

  $('directory').innerHTML="<div style='color:#7ff'>...</div>";
  current = -1;

  if (dir=='' && rootDirs!=undefined)
    {
      items=rootItems;
      dirs=rootDirs;
      dirLoaded();
    }
  else
    {
  new net.get(rootPath+dir,
    function(){
      var htmlIndex= this.req.responseText;
      var regexp = new RegExp('[a] *href=["\'](.*?)[\'"]', "gi");
      var result;

      items = new Array;
      dirs = new Array;

      { /* This parsing should accomodate for most html documents,
           and at least it seems to work for apache listings.
         */
        while (result = regexp.exec(htmlIndex))
          if (result && !result[1].match(/^#/) &&
                        !result[1].match(/^\//) &&
                        !result[1].match(/^\?/) &&
                        !result[1].match(/^http/))
            {
              add_item(dir+result[1]);
            }
        }
      dirLoaded();

    }, "GET");
}
  return;
}

window.onkeydown=function(event)
{
  var key;
  if (!event)
    var event = window.event;
  if (window.event)
    key = window.event.keyCode;
  else if (event.which)
    key = event.which;
  else
    return true;

  if (!key)
    return true;

  var key_backspace = 8;
  var key_tab = 9;
  var key_comma = 188;
  var key_period = 190;
  var key_space = 32;
  var key_left = 37;
  var key_right = 39;
  var key_0 = 48;
  var key_1 = 49;
  var key_f = 70;
  var key_s = 83;

  switch (key)
    {
      case key_right: buttonNext();   break;
      case key_backspace:
      case key_left:  buttonPrev();   break;
      case key_tab:   buttonRandom(); break;
      case key_space: buttonSlide();  break;
      case key_f:     buttonFull();   break;
      case key_1:     zoomNormal();   break;
      case key_0:     zoomFit();      break;
      case key_period:zoomIn();       break;
      case key_comma: zoomOut();      break;
      default:
        //alert("unhandled keycode " + key);
    }
}

function button(icon, blurb, id, action)
{
  return "<span style='cursor:pointer;' onmouseover='$(\"chelp\").innerHTML=\"" + blurb + "\";' onmouseout='$(\"chelp\").innerHTML=\"\";' id='"+id+"' onclick='"+action+"'>"+icon+"</span>";
}

window.onload=function()
{
  var urlquery = window.location.hash;
  var id = 'directory';

  window.fullscreen = true;

  if (!urlquery)
    {
      urlquery = "";
    }
  urlquery = urlquery.replace(/^#/,"");
  var i=0;

  $('controls').innerHTML= 
       "<span id='chelp'></span>"+
       button ("‣", 'Start slideshow',  'slide', 'buttonSlide()') +
       //button ("⚅", 'Random item',    'random', 'buttonRandom()') +
       button ("⊕", 'Zoom in',          'zoomin', 'zoomIn()') +
       button ("⊖", 'Zoom out',         'zoomout', 'zoomOut()') +
       button ("⊙", 'Zoom fit',         'zoomfit', 'zoomFit()') +
       button ("⊜", 'Zoom normal',      'zoomnormal', 'zoomNormal()') +
       button ("◅", 'Previous Item',    'prev', 'buttonPrev()') +
       button ("▻", 'Next Item',        'next', 'buttonNext()') +
       button ("⊚", 'Fill window',      'full', 'buttonFull()') +
"<div style='width:1px;height:1px' id='prevPreview'></div>"+
"<div style='width:1px;height:1px;position:fixed;top:0;right:0' id='nextPreview'></div>";
  //loadDir(urlquery);
  noSelect ();
  setInterval(sanitize, 1*200);
}

var net = new Object();
net.get=function(url,onload,onerror)
{
  this.url=url;
  this.req=null;
  this.onload=onload;
  this.onerror=(onerror)?onerror:this.defaultError;
  this.loadXMLDoc(url);
}

net.get.prototype=
{
  loadXMLDoc:function(url)
    {
      if (window.XMLHttpRequest)
        {
          this.req=new XMLHttpRequest();
        }
      else if (window.ActiveXObject)
        {
          this.req=new ActiveXObject("Microsoft.XMLHTTP");
        }
      if (this.req)
        {
          try
            {
              var loader=this;
              this.req.onreadystatechange=function()
                {
                  loader.onReadyState.call(loader);
                }
              this.req.open('GET',url,true);
              this.req.send(null);
            }
          catch (err)
            {
              this.onerror.call(this)
            }
        }
    },
  onReadyState:function()
    {
      var req=this.req;
      var ready=req.readyState;

      if (ready==4)
        {
          var httpStatus=req.status;
          if (httpStatus == 200 || httpStatus == 0)
            {
              this.onload.call(this);
            }
          else
            {
              this.onerror.call(this);
            }
        }
  },
  defaultError:function()
  {

    $('content').innerHTML="<h1>"+this.req.status + "</h1><p>Problem fetching data:</p>" + 
          "<dl><dt>url</dt><dd>"+ this.url +
          "</dd><dt>ReadyState:</dt><dd>"+this.req.readyState +
          "</dd><dt>Status:</dt><dd>"+this.req.status + 
          "</dd><dt>headers:</dt><dd><pre>"+this.req.getAllResponseHeaders() +"</pre></dd>"+"</dl>";

  }
}

function importStatic (id, URI)
{
  $(id).innerHTML="loading"
  new net.get(URI, 
    function(){
      $(id).innerHTML=this.req.responseText;
    });
}

function importPre (id, URI)
{
  $(id).innerHTML="loading"
  new net.get(URI,
    function(){
      content = this.req.responseText;
      content=content.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
      content="<pre>"+content+"</pre>"
      $(id).innerHTML=content;
    });
}
var lock = false;

var drag = new Object();

function drag_start (event)
{
  var id = 'image'
  var el;
  var x, y;
  resizeView();
  if (lock)
    return;
  lock = true;
  drag.element = $(id);
  x = event.clientX;
  y = event.clientY;
  drag.previousX = x;
  drag.previousY = y;
  if (document.addEventListener)
  {
      document.addEventListener("mousemove", drag_motion,   true);
      document.addEventListener("mouseup",   drag_end, true);
      event.preventDefault();
  }
  else if (document.attachEvent)
    {
      document.attachEvent("onmousemove", drag_motion);
      document.attachEvent("onmouseup",   drag_end);
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
  return false;
}

function drag_motion(event)
{
  var x, y;
  var dx, dy;
  x = event.clientX;
  y = event.clientY;
  dx = x - drag.previousX;
  dy = y - drag.previousY;
  drag.previousX = x;
  drag.previousY = y;
  
  /* do stuff with dx/dy */

  imageTop = imageTop - dy;
  imageLeft = imageLeft - dx;
  $('image').style.top =  (-imageTop) + "px";
  $('image').style.left =  (-imageLeft) + "px";
  updateNavigator();

  if (event.preventDefault)
  {
    event.preventDefault();
  }
  else if(window.event)
    {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }

}

function drag_end(event)
{
  if (document.removeEventListener)
  {
      document.removeEventListener("mousemove", drag_motion, true);
      document.removeEventListener("mouseup", drag_end, true);
  }
  else
   {
      document.detachEvent("onmousemove", drag_motion);
      document.detachEvent("onmouseup", drag_end);
    }
  lock = false;
}



/***********************************************
* Disable select-text script- © Dynamic Drive (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
* Modified here to exclude form tags properly, cross browser by jscheuer1
***********************************************/

//form tags to omit:
var omitformtags=["input", "textarea", "select", "p", "pre", "h1"]

function disableselect(e){
for (i=0;i<omitformtags.length;i++)
if (omitformtags[i]==(e.target.tagName.toLowerCase()))
return;
return false
}

function reEnable(){
return true
}

function noSelect(){
if (typeof document.onselectstart!="undefined"){
document.onselectstart=new Function("return false")
if (document.getElementsByTagName){
tags=document.getElementsByTagName('*')
for (j=0;j<tags.length;j++){
for (i=0;i<omitformtags.length;i++)
if (tags[j].tagName.toLowerCase()==omitformtags[i]){
tags[j].onselectstart=function(){
document.onselectstart=new Function('return true')
}
if(tags[j].onmouseup!==null){
var mUp=tags[j].onmouseup.toString()
mUp='document.onselectstart=new Function (\'return false\');\n'+mUp.substr(mUp.indexOf('{')+2,mUp.lastIndexOf('}')-mUp.indexOf('{')-3);
tags[j].onmouseup=new Function(mUp);
}
else{
tags[j].onmouseup=function(){
document.onselectstart=new Function('return false')
}
}
}
}
}
}
else{
document.onmousedown=disableselect
document.onmouseup=reEnable
}
}


function addEvent( obj, type, fn ) {
        if (obj.addEventListener) {
                obj.addEventListener( type, fn, false);
                EventCache.add(obj, type, fn);
        }
        else if (obj.attachEvent) {
                obj["e"+type+fn] = fn;
                obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
                obj.attachEvent( "on"+type, obj[type+fn] );
                EventCache.add(obj, type, fn);
        }
        else {
                obj["on"+type] = obj["e"+type+fn];
        }
}

var EventCache = function(){
        var listEvents = [];
        return {
                listEvents : listEvents,
                add : function(node, sEventName, fHandler){
                        listEvents.push(arguments);
                },
                flush : function(){
                        var i, item;
                        for(i = listEvents.length - 1; i >= 0; i = i - 1){
                                item = listEvents[i];
                                if(item[0].removeEventListener){
                                        item[0].removeEventListener(item[1], item[2], item[3]);
                                };
                                if(item[1].substring(0, 2) != "on"){
                                        item[1] = "on" + item[1];
                                };
                                if(item[0].detachEvent){
                                        item[0].detachEvent(item[1], item[2]);
                                };
                                item[0][item[1]] = null;
                        };
                }
        };
}();
addEvent(window,'unload',EventCache.flush);


