//
// Copyright (c) 2008-2009 Beyond360 Imaging LLC. All rights reserved.
//
// 4/22/2009:
// New animation (no autospin) - eventually this could be set in calling file
// No slider support
// Supports min/max/step zoom
// Supports variable spin rate (FPS)
// 06/02/2009: Fix undefined variable caused by incomplete load in IE 
// 06/03/2009: Add variable to control spin on mousemove (aka autospin, the "old" navigation) 
// 06/13/2009: Decide whether we should stop the animation on mousedown
// 07/12/2009: Added function newZoom that enables a popup with lens zoom
// 08/29/2009: Add workaround for images not panning when slider not around (Task #79) 
// 09/24/2010: Add support for touch-based navigation (task #127)
//
//  var fps = 5; // only used in one function no longer global
//  var step = 10;

  var loadMouseHandler = true;
  var thumbWindow = null;
  var adminWindow = null;
  var timer = null;
  var thumbs = null;
  var elev = 0;
  var animwidth = 0;
  var animheight = 0;
  var prevmousex = 0;
//  var frame_count = 0;
  var frame_load_count = 0;
  var frames_loaded = false;
  var start_on_load = false;
  var stopLoad = false;
  var frameNumber = 0;
  var animIncrement = 1;
  var frames = []; // new Array();
  var firstimage = new Image();
  var anim_area = {}; // new Object();
  var hs_area = {}; // new Object();
  var min_x_delta = 4;
  var spinOnMouseMove = false;       // RCL disable spinning the image when mouse moves across it
//  var newzoomStat = 0;             // RCL keeps track of status of the new zoom type
  var gZoomQuadrant=0; // 0 = upper right, 1 = lower right, 2 = lower left, 3 = upper left
  
  function basename(path)
  {
    var pattern = /^(.*\/)?(.*)/;
    var rc = path.match(pattern);
    return rc[2];
  }

  function makeThumb(save)
  {
    var currentFrame = $('imgload').src;
    var bn = basename(currentFrame);
//    var thumbURL = encodeURI(baseURL + prodID + "/zoom/5/" + bn);
    var URL = "/makethumb.php?ID=" + prodID + "&thumb=" + bn;

    if (save === true)
    {
      URL = URL + "&save=1";
    }

    thumbWindow = window.open(URL, "thumbwin", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=400,left=10,top=10");
  }

  function popAdmin()
  {
    var URL = "/admin.php?ID=" + prodID;

    adminWindow = window.open(URL, "adminwin", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=400,left=10,top=10");
  }

  function popUp(URL,x,y,l,t)
  {
    day = new Date();
    id = day.getTime();
    //eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width="+x+",height="+y+",left="+l+",top="+t+"');");
    window.open(URL, "B360_Print", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width="+x+",height="+y+",left="+l+",top="+t);
  }

// RCL Add support for new type of zoom
// Toggles on/off each time it's called
// z is large zoom level
function newZoom(z)
{
  if (isNaN(z))
  {
    z = 40; // pick 40 arbitrarily as the level of zoom by default
  }


  var pattern = /^(.*\.)+(.*)/;
  
  var currentFrame = $('imgload').src;
  var bn = basename(currentFrame);
  var rc = bn.match(pattern);
  var lg = baseURL + prodID + "/zoom/" + z + "/" + bn;
  var sm = baseURL + prodID + "/zoom/" + zoomFactor + "/" + bn;
  var i_sm = new Image();
  i_sm.src = sm;
  //var ht = eval (i_sm.height > 280 ? i_sm.height : 280);
  //var w = eval (i_sm.width + 280);
  var ht = (i_sm.height > 280) ? i_sm.height : 280;
  var w = i_sm.width + 280;
  //alert ("h = " + ht + "w = " + w);
  window.open("newzoom.php?img_lg=" + lg + "&img_sm=" + sm,"Hoverzoom","width=" + w + ",height=" + ht + ",resizable=no,toolbar=no,location=no,directories=no");  
}
  function printanim()
  {
    var pattern = /^(.*\.)+(.*)/;

    var currentFrame = $('imgload').src;
    var bn = basename(currentFrame);
    var rc = bn.match(pattern);

    var URL = baseURL + prodID + "/zoom/100/" + bn;		// Fullsize image URL
    popUp(URL, 800, 600, 0, 0);
    anim_area.pan_on = true;

    // Google Analytics
    trackGA("NAVIGATION", "View100", "NA", 0);
  }

  function displayNextFrame()
  {
    var pattern = /^.*\/(\d{1,2})\/(\d{1,3})-(\d{1,3})\.([a-zA-Z]+)/;
    if (viewerType === 0)
    {
        //alert ("Viewertype is " + viewerType);
        return;
    }


    // RCL DEBUG: try to fix IE issue where one or more of these variables are undefined at this point
    //if (frameNumber < 10)  // so that it doesn't go on alerting forever
    //alert ("Framenumber is " + frameNumber + ", animIncrement is " + animIncrement);
    if (isNaN(frameNumber))
    {
      frameNumber = 0;
    }
    if (isNaN(animIncrement))
    {
      animIncrement = 1; // RCL make this 0 to fix the hover-reload issue [HACK]
    }
    var frame = frameNumber + animIncrement;

    //if (frameNumber < 10) 
    //  alert ("Framenumber is " + frameNumber + ", frame is " + frame);
    if (frame >= frame_count)
    {
      frame = 0;
    }
    else if (frame < 0)
    {
      frame = frame_count - 1;
    }

    frameNumber = frame;

    var src = frames[frameNumber].src;
    $('imgload').src = src;

    var test = src.match(pattern);			// 1=>zoom, 2=>inclination, 3=>rotation
    var view = test[2] + "-" + test[3];

    // Check the spots to see if any need to be displayed. When a dot is defined, the corresponding hs 
    // popup will be displayed for 3 frames. The dots will not be displayed in autospin because the 
    // viewer (user) has no control of the mouse.
    checkHotSpots (test[1], view);

    return; 
  }

  function animationStop()
  {
    if (timer)
    {
      clearInterval(timer);
    }

    timer = null;
//    frameNumber = 0;

//    anim_area.pan_on = true;
    prevmousex = 0;
//    $('xval').value = 'Start observing';

    if (frame_load_count == frame_count)
    {
        changeZoomImage ();
    }
  } // animationStop

// fps is optional and will default if omitted
  function animationStart(dir, fps)
  {
    // Do not start animation unless all the frames are fully loaded, otherwise
    // some global variables may not be defined at this point
    // TaskList item 68
    if (frames_loaded === false)
    {
        return;
    }

    if (viewerType === 0)
    {
      return;
    }

    if ((typeof(fps) == 'undefined') || (fps <= 0))
    {
      //alert ("WARNING: FPS is " + fps);
      fps = 10; // default
    }
    if ((typeof(dir) == 'undefined') || isNaN(dir))
    {
      //alert ("WARNING: dir is undef");
      dir = 1; // default
    }
    anim_area.pan_on = false;
    prevmousex = 0;
    animIncrement = dir;

    if (timer !== null)
    {
        if ((gStopAfterFrame) || (gStopAnimAfterThisFrame))
        {
            gStopAnimAfterThisFrame = false;
            animationStop();
        }
        return;	        // Timer already started
    }

    if (! frames_loaded)
    {
      start_on_load = true;
    }
    else
    {
      displayNextFrame();

      // mp: Stop after every image when user specifies discrete angles
      if ((!gStopAfterFrame) && (!gStopAnimAfterThisFrame))
      {
        timer = setInterval(displayNextFrame, (1000 / fps));
      }
      else
      {
        gStopAnimAfterThisFrame = false;
      }
    }

    // Google Analytics
    if (dir == -1)
    {
        trackGA("NAVIGATION", "RotateLeft", "NA", 0);
    }
    else
    {
        trackGA("NAVIGATION", "RotateRight", "NA", 0);
    }
  }

  function repositionImage()
  {
    var wid = firstimage.width;
    var ht = firstimage.height;

    var xoffset = anim_area.center_x - Math.round(wid / 2);
    var yoffset = anim_area.center_y - Math.round(ht / 2);

    anim_area.img_pos_left = xoffset;
    anim_area.img_pos_top = yoffset;

    $('imgload').src = firstimage.src;
    $('imgload').style.left = xoffset + "px";
    $('imgload').style.top = yoffset + "px";

    //    Position.absolutize('imgload');
    initHotspots(xoffset, yoffset);
    //showHelpTip (true); // mtp: Works here too and centered properly, but a little too late

    if (debug)
    {
      $('xval').innerHTML = "anim_area.width: "+anim_area.dimensions.width+"\nanim_area.height: "+anim_area.dimensions.height+"\nwidth: "+wid+"\nheight: "+ht+"\nxoffset: "+xoffset+"\nyoffset: "+yoffset+"\nApp: "+navigator.appName+"\nVer: "+navigator.appVersion;
    }
  }

  function countLoadedFrames()
  {
    frame_load_count++;
//    $('xval').value = frame_load_count;
    if (frame_load_count == frame_count)
    {
        var angle = frameNumber * step;
        checkHotSpots (zoomFactor + '', elev + '-' + angle);
        // checkHotSpots (zoomFactor + '', '0-0');

      // showHelpTip (true); // mtp: this does NOT work here

      min_x_delta = Math.ceil(144 / frame_count);
      frames_loaded = true;
      documentOnloadHandler ("imagesLoaded");
      if (gAutoSpin == 1)     // mtp: Issue 92
      {
        start_on_load = true;
      }

      if (start_on_load)
      {
       // animationStart();
        // animationStart(1, fps);  // mtp: Issue 92
        animationStart(-1, fps);  // -1 to the left, 1 to the right
      }
      else
      {
        anim_area.pan_on = true;
      }
    }
  }

// RCL: this function adapted from http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/
function touchHandler(event)
{
  //alert ('In touchhandler. Event: ' + event.type);
  var touches = event.changedTouches,
    first = touches[0],
    type = "";
  switch(event.type)
    {
    case "touchstart": type="mousedown"; break;
    case "touchmove":  type="mousemove"; break;
    case "touchend":   type="mouseup"; break;
    default: return;
    }

  // now create a simulated mouse event of the proper type
  var simulatedEvent = document.createEvent("MouseEvent");
  simulatedEvent.initMouseEvent(type, true, true, window, 1, 
				first.screenX, first.screenY, 
				first.clientX, first.clientY, false, 
				false, false, false, 0/*left*/, null);

  first.target.dispatchEvent(simulatedEvent);
  // Prevent browser from receiving the event
  event.preventDefault();
}


  function mouseHandler(evt)
  {
    var pattern = /^(\d*)px/;

    var mousex = Event.pointerX(evt);
    var mousey = Event.pointerY(evt);
    
    if (isNaN(clickStopsSpin))
    {
      //alert ("clickstopsspin is undef");
      clickStopsSpin = 0; // default in case undefined
    }
    if (anim_area.prev_mouse_x === undefined)
    {
      anim_area.prev_mouse_x = mousex;
      anim_area.prev_mouse_y = mousey;
      //alert ('animarea pmouse: x = ' + mousex + '; y= ' + mousey);
    }

    var deltax = mousex - anim_area.prev_mouse_x;
    var deltay = mousey - anim_area.prev_mouse_y;

    //alert ('x: '+mousex+'\ny: '+mousey+'\ndeltax: '+deltax+'\ndeltay: '+deltay);
    if (debug)
    {
      $('xval').innerHTML = 'x: '+mousex+'\ny: '+mousey+'\ndeltax: '+deltax+'\ndeltay: '+deltay;
    }

    //    var dx = anim_area.center_x - mousex;
    //    var dy = anim_area.center_y - mousey;
    //    $('topright').innerHTML = 'x: '+dx+'   y: '+dy;

    //if (drag == 1)
    //    $('animarea').style.cursor = "move"; // mtp: Fix for issue 88

    //if (gDragRotateOn == true)
    //    $('animarea').style.cursor = "e-resize";

    switch (evt.type)
      {
      case "mouseout":
        Element.hide('zoomDiv');
        $('animarea').style.cursor = "default";
        break;

      case "mouseover":
        setCursor ();
        if (gZoomActive)
        {
            Element.show('zoomDiv');
        }
        break;

      case "mousedown":
        // When mouse is down, zoom mode is automatically OFF
        gSavedZoomState = gZoomActive;
        zoomModeControl ("off");
	//alert('Mousedown, Event is ' + evt);
        // RCL Decide whether we should stop the animation on mousedown
        //alert ("b360animatornew-ns1: Mouse down. stopspin is " + clickStopsSpin);	
        if (clickStopsSpin == 1)
        {
            animationStop();
        }

        if (gMouseFunction == "mf_rotate")
        {
            gDragRotateOn = true;
            //$('animarea').style.cursor = "e-resize";
        }
        // else if (drag == 1)
	//alert ('mousedown and move');
        if (gMouseFunction == "mf_move")
        {
            anim_area.pan_on_save = anim_area.pan_on;
            anim_area.pan_on = false;
            anim_area.drag_on = true;
	  
            deltax = 0;					// This fixes "jump problem"
            deltay = 0;
            anim_area.prev_mouse_x = mousex;
            anim_area.prev_mouse_y = mousey;		// End of fix

            // $('animarea').style.cursor = "move"; // RCL: Now can only move in animarea, set in css
        }

        // Google Analytics
        trackGA("NAVIGATION", "Mouse.Click", "NA", 0);
        break;

      case "mouseup":
	//alert ('In mouseup handler.' + event.type);
	// If we've moused down or touched a hotspot
	if (evt.target.id.indexOf('hsmark') >= 0) {
	  var parts = new Array();
	  parts = evt.target.id.split('hsmark');
	  if (!isNaN(parts[1]) && parts[1] >= 0) {
	    showHSInfo(parts[1]);
	  }
	}
	
        // zoomToggleAction ();
        changeZoomImage ();
        if (gSavedZoomState)
        {
            zoomModeControl ("on");
        }
        else
        {
            zoomModeControl ("off");
        }

        if (gMouseFunction == "mf_rotate")
        {
            gDragRotateOn = false;
            //$('animarea').style.cursor = "e-resize";
        }
        if (Math.abs(deltax) < 10)
        {
          anim_area.pan_on = (anim_area.pan_on_save ? false : true);
        }
        else
        {
          anim_area.pan_on = true;
        }

        anim_area.drag_on = false;
        //$('animarea').style.cursor = "default"; // RCL: Now can only move in animarea

        break;

      case "mousemove":
        // RCL: if ((anim_area.pan_on) && (viewerType != 0))
	// alert ('Mousemove. gShowZoom=' + gShowZoom + '; gZoomActive=' + gZoomActive);
        // Zoom Mode
        if ((gShowZoom == 2) && (gZoomActive === true))
        {
	    //alert ('Inside showzoom if. gShowZoom=' + gShowZoom + '; gZoomActive=' + gZoomActive);
            $('animarea').style.cursor = "crosshair";
            if ((mousex >= (anim_area.img_pos_left - 10)) && 
                (mousex < (anim_area.img_pos_left + firstimage.width + 10)) &&
                (mousey >= (anim_area.img_pos_top - 10)) &&
                (mousey < (anim_area.img_pos_top + firstimage.height + 10)))
            {
		//alert ('Inside mousexy if. x=' + mousex + '; y=' + mousey);
                var zWidth = $('zoomDiv').getWidth ();
                var zHeight = $('zoomDiv').getHeight ();
                var animLeft = parseInt ($('animarea').getStyle ('left'), 10);
                var animTop = parseInt ($('animarea').getStyle ('top'), 10);
                var dX = anim_area.img_pos_left - animLeft + gZoomOffsetX;
                var dY = anim_area.img_pos_top - animTop + gZoomOffsetY;

                var zoomScale = gZoomFunctionLevel/zoomFactor;
                //var newX = ((mousex - dX) * zoomScale) - $('zoomDiv').getWidth ()/2;
                //var newY = ((mousey - dY) * zoomScale) - $('zoomDiv').getHeight ()/2;
                var newX = ((mousex - dX) * zoomScale) - zWidth/2;
                var newY = ((mousey - dY) * zoomScale) - zHeight/2;
                var newBgPos = (0 - newX) + "px " + (0 - newY) + "px";
                $('zoomDiv').setStyle({backgroundPosition: newBgPos});

                // Debug stuff
                // document.getElementById('zoomPos').innerHTML = "X:" + mousex + " Y: " + mousey + "<br>nX: " + newX + "<br>nY: " + newY;
                // document.getElementById('zoomPos').innerHTML = "X:" + mousex + " Y: " + mousey + "<br>dX: " + anim_area.img_pos_left + "<br>dY: " + anim_area.img_pos_top;
                // document.getElementById('zoomPos').innerHTML = "X:" + mousex + " Y: " + mousey;
                //document.getElementById('zoomPos').innerHTML = "dX:" + deltax + " dY: " + deltay;

                var bufferZone = 10; // pixels
                var zoomPosX;
                var zoomPosY;

                switch (gZoomQuadrant)
                {
                    case 0: // upper right
                        $('zoomDiv').setStyle({top: mousey - $('zoomDiv').getHeight () - bufferZone + 'px', left: mousex + bufferZone + 'px'});
                        if ((mousex + zWidth + bufferZone) > anim_area.dimensions.width)
                        {
                            gZoomQuadrant = 3; // switch to upper left
                        }

                        if ((mousey - zHeight - bufferZone) < 0)
                        {
                            gZoomQuadrant = 1;
                        }
                        break;

                    case 1: // lower right
                        $('zoomDiv').setStyle({top: mousey + bufferZone + 'px', left: mousex + bufferZone + 'px'});
                        if ((mousex + zWidth + bufferZone) > anim_area.dimensions.width)
                        {
                            gZoomQuadrant = 2; // switch to lower left
                        }
                        if ((mousey + zHeight + bufferZone) > anim_area.dimensions.height)
                        {
                            gZoomQuadrant = 0;
                        }
                        break;

                    case 2: // lower left
                        $('zoomDiv').setStyle({top: mousey + bufferZone + 'px', left: mousex - $('zoomDiv').getWidth () - bufferZone + 'px'});
                        if ((mousex - zWidth - bufferZone) < 0)
                        {
                            gZoomQuadrant = 1; // switch to lower right
                        }
                        if ((mousey + zHeight + bufferZone) > anim_area.dimensions.height)
                        {
                            gZoomQuadrant = 3;
                        }
                        
                        break;

                    case 3: // upper left
                        $('zoomDiv').setStyle({top: mousey - $('zoomDiv').getHeight () - bufferZone + 'px', left: mousex - $('zoomDiv').getWidth () - bufferZone + 'px'});
                        if ((mousex - zWidth - bufferZone) < 0)
                        {
                            gZoomQuadrant = 0;
                        }
                        if ((mousey - zHeight - bufferZone) < 0)
                        {
                            gZoomQuadrant = 2;
                        }
                        break;
                }
                $('zoomDiv').show ();
            }
            else
            {
		//alert ('Mouse-rotate');
                $('zoomDiv').hide ();
                if (gMouseFunction == "mf_rotate")
                {
                    $('animarea').style.cursor = "e-resize";
                }
                else
                {
                    $('animarea').style.cursor = "move";
                }
            }
        }

        //if ((gMouseFunction == "mf_rotate") && (gDragRotateOn == true))
        else if ((gMouseFunction == "mf_rotate") && (gDragRotateOn === true)) // the "else" is for testing only
        {
	    //alert ('in elseif. gMouseFunction = ' + gMouseFunction + '; dragrotate = ' + gDragRotateOn + '; deltax = ' + deltax);
            if (Math.abs(deltax) >= min_x_delta)			// Make sure we've moved at least 4 pixels for a 36 frame sequence;
            {
                anim_area.prev_mouse_x = mousex;
                anim_area.prev_mouse_y = mousey;
                if (deltax > 0)
                {
                    animIncrement = 1;
                }
                else
                {
                    animIncrement = -1;
                }
                displayNextFrame();
            }
        }

        /*
        else if (spinOnMouseMove) // RCL disable automatic spinning when mouse moves
        {
          if (Math.abs(deltax) >= min_x_delta)			// Make sure we've moved at least 4 pixels for a 36 frame sequence;
          {
            anim_area.prev_mouse_x = mousex;
            anim_area.prev_mouse_y = mousey;
            if (deltax > 0)
              animIncrement = 1;
            else
              animIncrement = -1;

            displayNextFrame();
          }
        } */
        else if (anim_area.drag_on)
        {
          anim_area.prev_mouse_x = mousex;
          anim_area.prev_mouse_y = mousey;
          anim_area.center_x += deltax;
          anim_area.img_pos_left += deltax;
          $('imgload').style.left = anim_area.img_pos_left + "px";

          anim_area.center_y += deltay;
          anim_area.img_pos_top += deltay;
          $('imgload').style.top = anim_area.img_pos_top + "px";

          hs_area.left += deltax;
          hs_area.top += deltay;

          $('hslayer').style.left = hs_area.left + "px";
          $('hslayer').style.top = hs_area.top + "px";
        }
        break;
    }
    Event.stop(evt);			// Prevent event from propagating through to browser built-in function
  }

  function buildAnim()
  {
    var URL; //  = new String();

    //checkPopupBlocker ();
    showHelpTip (true); // mtp: Works here. If not in event loadhandler, then should be here
    hideAllHotspots ();

    if (anim_area.dimensions === undefined)	// Check for uninitialized animation area
    {
      anim_area.dimensions = $('animarea').getDimensions();

      anim_area.center_x = Math.round(anim_area.dimensions.width / 2);
      anim_area.center_y = Math.round(anim_area.dimensions.height / 2);

      anim_area.pan_on = true;
      anim_area.drag_on = false;

      hs_area.left = 0;
      hs_area.top = 0;
    }
    // showHelpTip (true); // mtp: this works here
    repositionB360 ();
    animationStop();

    if (loadMouseHandler)
    {
      // add touch event detection
      Event.observe($('animarea'), "touchmove", touchHandler);
      Event.observe($('animarea'), "touchstart", touchHandler);
      Event.observe($('animarea'), "touchend", touchHandler);
      Event.observe($('animarea'), "mousemove", mouseHandler);
      Event.observe($('animarea'), "mousedown", mouseHandler);
      Event.observe($('animarea'), "mouseup", mouseHandler);
      Event.observe($('animarea'), "mouseout", mouseHandler);
      Event.observe($('animarea'), "mouseover", mouseHandler);

      // Currently being tested: Handle control key detection
      //Event.observe($('hsToggleButton'), "keydown", keyDownHandler);
      //Event.observe($('hsToggleButton'), "keyup", keyUpHandler);
      document.observe('keydown', keyDownHandler);
      document.observe('keyup', keyUpHandler);

      loadMouseHandler = false;
    }

//    Position.absolutize('animarea');
//    Position.absolutize('btns');
    Position.absolutize('hslayer');
    //Position.absolutize('hsinfo');

    if (viewerType > 0)
    {
      stopLoad = false;
      frame_load_count = 0;

//      var angle = frameNumber * 10;
      var angle = frameNumber * step;
      var frame = frameNumber;

      for (var i = 0; i < frame_count; i++)
      {
        if (stopLoad)
        {
          stopLoad = false;
          break;
        }
        else
        {
          URL = baseURL + prodID + "/zoom/" + zoomFactor + "/" + elev + "-" + angle + "." + anim_ext;
          frames[frame] = new Image();
          frames[frame].src = URL;
		  // Since MSIE will not fire an "onload" event after the image
		  // has been cached, we have to check to see if the image has
		  // been loaded or not and call the function countLoadedFrames
		  // appropriately. Tasklist items 60 and 65
          //if (isIE())
          if ((frames[frame].complete === true) && (frames[frame].width > 0))
          {
              countLoadedFrames();
          }
          else
          {
              frames[frame].onload = countLoadedFrames;
          }

          frame = (frame + 1) % frame_count;
//          angle = (angle + 10) % (frame_count * 10);
          angle = (angle + step) % (frame_count * step);

          // mp: Probably don't want to do this until all images are loaded
          if (i === 0)
          {
            firstimage.src = URL;
		    // Since MSIE will not fire an "onload" event after the image
		    // has been cached, we have to check to see if the image has
		    // been loaded or not and call the function countLoadedFrames
		    // appropriately. Tasklist items 60 and 65
            //if (isIE())
			if ((firstimage.complete === true) && (firstimage.width > 0))
            {
			    repositionImage();
            }
			else
            {
                firstimage.onload = repositionImage;
            }
          } //
        }
      }
      getButtonImages ();
      //getZoomImages ();
    }
    if (gMouseFunctionInitialized === false)
    {
        mouseFunctionInit();
        hsButtonInit ();
        gMouseFunctionInitialized = true;
        //showHelpTip (true);
        //gOrigZoom = zoomFactor;
        
    }
    //showHelpTip (true);
  } // buildAnim

  function stillimg(thumb_id)
  {
    var image_is_new = true;
    var URL; // = new String();
    var pattern = /^(\d{1,3})-(\d{1,3})\.([a-zA-Z]+)/;

    animationStop();
    if (prodID == thumbs[thumb_id][0])
    {
      image_is_new = false;
    }

    prodID = thumbs[thumb_id][0];		// FIXME
    viewerType = thumbs[thumb_id][1];
    var bn = basename(thumbs[thumb_id][2]);
    fullwid = thumbs[thumb_id][3];
    fullht = thumbs[thumb_id][4];
    frame_count = thumbs[thumb_id][5];
    max_elev = thumbs[thumb_id][6];

    var wid = zoomFactor * 0.01 * fullwid;
    var ht = zoomFactor * 0.01 * fullht;
    $('imgload').width = wid;
    $('imgload').height = ht;

    var xoffset = anim_area.center_x - Math.round(fullwid / 2);
    var yoffset = anim_area.center_y - Math.round(fullht / 2);

    anim_area.img_pos_left = xoffset;
    anim_area.img_pos_top = yoffset;

    $('imgload').style.left = xoffset + "px";
    $('imgload').style.top = yoffset + "px";


    initHotspots(xoffset, yoffset);

    URL = baseURL + prodID + "/zoom/" + zoomFactor + "/" + bn;

    firstimage.src = URL;
	// Since MSIE will not fire an "onload" event after the image
	// has been cached, we have to check to see if the image has
	// been loaded or not and call the function countLoadedFrames
	// appropriately. Tasklist items 60 and 65
	if ((firstimage.complete === true) && (firstimage.width > 0))
    {
		repositionImage();
    }
	else
    {
        firstimage.onload = repositionImage;
    }

    $('imgload').src = URL;  // mtp: not until all images have been loaded

    var rot = bn.match(pattern);
//    frameNumber = rot[2] / 10;			// FIXME
    frameNumber = rot[2] / step;

    if (image_is_new)
    {
      buildAnim();
    }
  }


  function zoomIn()
  {
    // drag = 1; // mtp: requested by Chris
    if (zoomFactor < maxZoom)
    {
      stopLoad = true;
      zoomFactor += zoomStep;

      var wid = zoomFactor * 0.01 * fullwid;
      var ht = zoomFactor * 0.01 * fullht;
      $('imgload').width = wid;
      $('imgload').height = ht;

      var xoffset = anim_area.center_x - Math.round(wid / 2);
      var yoffset = anim_area.center_y - Math.round(ht / 2);

      anim_area.img_pos_left = xoffset;
      anim_area.img_pos_top = yoffset;

      $('imgload').style.left = xoffset + "px";
      $('imgload').style.top = yoffset + "px";

      hideAllHotspots ();
      buildAnim();
    }
    trackGA("NAVIGATION", "Zoom.In", "NA", 0);
  }

  function zoomOut()
  {
    // drag = 1; // mtp: Requested by Chris
    if (zoomFactor > minZoom)
    {
      stopLoad = true;
      zoomFactor -= zoomStep;

      var wid = zoomFactor * 0.01 * fullwid;
      var ht = zoomFactor * 0.01 * fullht;
      $('imgload').width = wid;
      $('imgload').height = ht;

      var xoffset = anim_area.center_x - Math.round(wid / 2);
      var yoffset = anim_area.center_y - Math.round(ht / 2);

      anim_area.img_pos_left = xoffset;
      anim_area.img_pos_top = yoffset;

      $('imgload').style.left = xoffset + "px";
      $('imgload').style.top = yoffset + "px";

      hideAllHotspots ();
      buildAnim();
    }
    trackGA("NAVIGATION", "Zoom.Out", "NA", 0);
  }

  function tiltDown()
  {
    if (elev < max_elev)			// FIXME
    {
      elev += 10;
      buildAnim();
    }
  }

  function tiltUp()
  {
    if (elev > 0)				// FIXME
    {
      elev -= 10;
      buildAnim();
    }
  }

  function changeview(selector)
  {
    var textsel = selector.value;
    var elem = "";

    for (var x = 1; x <= 5; x++)
    {
      elem = "lvl" + x;
      $(elem).style.display = "none";
    }

    $(textsel).style.display = "inline";
  }

  function showview(selector)
  {
    var elem = "";
    var idx = selector.substring(3);

    anim_area.pan_on = true;

    for (var x = 1; x <= 5; x++)
    {
      elem = "lvl" + x;
      $(elem).style.display = "none";
    }

    $("descriptor").selectedIndex = Number(idx - 1);
    $(selector).style.display = "inline";
  }

    function resetImg()
    {
        history.go(0);

        // Google Analytics
        trackGA("NAVIGATION", "Reset", "NA", 0);
    }

  function measure()
  {
    animationStop();
  }

  function resizeThumbs()
  {
    var ht = $('thumbbox').getHeight();
    ht -= 2;

    var children = $('thumbbox').immediateDescendants();
    for (var i=0; i<children.length; i++)
    {
      if (children[i].hasClassName('snapshot'))
      {
        children[i].setStyle({height: (ht)});
      }
    }
  }



