//
// Copyright (c) 2008-2009 Beyond360 Imaging LLC. All rights reserved.
//

// 4/22/2009: New animation (no autospin) in animarea, and add slider support
//            Supports variable spin rate (FPS)
// 6/02/2009: Fix undefined variable caused by incomplete load in IE 
// 6/03/2009: Add variable to control spin on mousemove (aka autospin, the "old" navigation) 
// 7/12/2009: Added function newZoom that enables a popup with lens zoom


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

  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

  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, "FULL_VIEW", "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
  }

  // toggle- not used right now
  /*
  if (newzoomStat == 0)
    newzoomStat = 1;
  else
    newzoomStat = 0;
  */

  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
//    var URL = baseURL + prodID + "/zoom/100/" + rc[1] + rc[2];	// Fullsize image URL
//    var URL = baseURL + prodID + "/zoom/100/" + rc[1] + "png";	// Fullsize image URL
//    var URL = "/fullsize.php?ID=" + prodID + "&fn=" + bn;	// Fullsize image URL
    popUp(URL, 800, 600, 0, 0);
    anim_area.pan_on = true;

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

// RCL in_val is the angle value to be updated on the slider.
// to actually update the slider, slider_update should be =1.
  function displayNextFrame(in_val,slider_update)
  {
    var pattern = /^.*\/(\d{1,2})\/(\d{1,3})-(\d{1,3})\.([a-zA-Z]+)/;

    if (viewerType === 0)
    {
      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 (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];
    //var hsdot = document.getElementById("hsdot");
    //var hsimg = document.getElementById("hsimg");
    //var hsinfo = document.getElementById("hsinfo");
    //var hstitle = document.getElementById("hstitle");

    // RCL BEGIN UPDATES FOR SLIDE
    // Either we get an update from the slide being manually moved (in_val)
    // or by the autorotation function (test[3]) which is the current photo
    // in_val should be called with a negative value in order for that to be ignored - in the case of autospin
    slide_update_val = test[3]; // default to current image name value;
    if (in_val >= 0)
    {
      slide_update_val = in_val;      
    }
    // Hack to avoid moving the slider to zero position if at the 360 position
    if (!(slider_update === 0 && in_val === 0))
    {
      //if (slider_update == 1)
      A_SLIDERS[0].f_setValue(slide_update_val,null,1); // RCL move slider to proper place based on photo angle
    }
    if (0) {    // enable for debug only
      if (in_val != test[3]) {
	document.getElementById("slidedebug").style = "color:red;";
	//alert ('value inequality');
      } else {
	document.getElementById("slidedebug").style = "color:white;";
      }
      document.getElementById("slidedebug").innerHTML = "DBG: slider val: " + in_val + "; photo angle: " + test[3];
    }
    if (0) {    // enable for debug only
      document.getElementById("slidedebug").innerHTML = "DBG: slider val: " + in_val + "; photo angle: " + test[3];
    }
    // RCL END UPDATES FOR SLIDE

/*
    hsdot.style.visibility = "hidden";

    for (var i = 0; i < spots_size; i++)
    {
      if ((spots[i][0] == test[1]) && (spots[i][1] == view)) // mp: test[1] = zoomLevel, spots[i][0] = zoomLevel, spots[i][1]=viewType
      {
        hsdot.style.left = spots[i][2] + "px";  // posX
        hsdot.style.top = spots[i][3] + "px";   // poxY
        hsdot.title = i;  // mp: Needed an ID so that mouse handler can identify which dot initiated the event
        // mtp hsdot.style.visibility = "visible";

        hsimg.src = spots[i][6];
        var wid = spots[i][4];
        var ht = spots[i][5];

//        if (ht < 197)
//        {
          ht += 2;				// FIXME: no scrollbars yet as we're doing the mouseover, mouseout thing
          wid += 2;
          hsinfo.style.height = ht + "px";
          hsinfo.style.width = wid + "px";
//        }
//        else
//        {
//          wid += 30;
//          hsinfo.style.height = "200px";
//          hsinfo.style.width = wid + "px";
//        }
      }
    } */

    // 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 (test[3]); // RCL: return the angle value of the image
  }


// fps is optional and will default if omitted
// dir is the direction of rotation (animation): -1=right (CW); 1=left (CCW)
  function animationStart(dir, fps)
  {
    //gDir = dir;

    // 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 (isNaN(fps) || (typeof(fps) == 'undefined') || (fps <= 0)) {
      fps = 10; // default
    }
    anim_area.pan_on = false;
    prevmousex = 0;
    animIncrement = dir;

    if (timer !== null)
    {
      return;				// Timer already started
    }

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

      // mp: Stop after every image when user specifies discreet angles
      if ((!gStopAfterFrame) && (!gStopAnimAfterThisFrame))
      {
        timer = setInterval("displayNextFrame(-1)", (1000 / fps));
      }
      else
      {
        gStopAnimAfterThisFrame = false;
      }
    }
    // Google Analytics
    if (dir == -1)
    {
        trackGA("NAVIGATION", "Rotate.Left", "NA", 0);
    }
    else
    {
        trackGA("NAVIGATION", "Rotate.Right", "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);

    // $('imgload').style.visibility = "visible";

    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');
      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 left, 1 right
      }
      else
      {
        anim_area.pan_on = true;
      }
    }
  }

  function animationStop()
  {
    if (timer)
    {
      clearInterval(timer);
    }
    timer = null;
//    frameNumber = 0;

//    anim_area.pan_on = true; // RCL don't allow panning anymore - but this may need the variable spinOnMouseMove
    prevmousex = 0;
//    $('xval').value = 'Start observing';
  } // animationStop

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

    var mousex = Event.pointerX(evt);
    var mousey = Event.pointerY(evt);

    if (anim_area.prev_mouse_x === undefined)
    {
      anim_area.prev_mouse_x = mousex;
      anim_area.prev_mouse_y = mousey;
    }

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

    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 issue 88
    }
    else
    {
        $('animarea').style.cursor = "default";
    }

    switch (evt.type)
    {
      case "mousedown":
        // RCL Decide whether we should stop the animation on mousedown
        if (clickStopsSpin == 1)
        {
            animationStop();
        }
        if (drag == 1)
        {
            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":
        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))
        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();

    showHelpTip (true); // mtp: Works here. If not in event loadhandler, then should be here
    hideAllHotspots ();
    if (gShowZoom == 2)
    {
        gShowZoom = 0;  // When the NAV contains the slider, there's no popup zoom
    }

    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;
    }

    animationStop();
    repositionB360 ();

    if (loadMouseHandler)
    {
      Event.observe($('animarea'), "mousemove", mouseHandler);
      Event.observe($('animarea'), "mousedown", mouseHandler);
      Event.observe($('animarea'), "mouseup", mouseHandler);
      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 ((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);

          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 ((firstimage.complete === true) && (firstimage.width > 0))
            {
			    repositionImage();
            }
			else
            {
                firstimage.onload = repositionImage;
            }
          }
        }
      }
      // Chris requested that animation starts at 350, not 0 degrees
      // but later requested this change to be retracted
      //A_SLIDERS[0].f_setValue((frame_count-1)*step, null, 1);

      //getButtonImages ();
    }
    if (gMouseFunctionInitialized === false)
    {
        //mouseFunctionInit();
        hsButtonInit ();
        gMouseFunctionInitialized = 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";

    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;

    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

    // Just in case we're being called from display.php without these defaults,
    // check and default them here
    if ((typeof(maxZoom) == 'undefined') || (maxZoom <= 0))
    {
      maxZoom = 100; // default
    }
    if ((typeof(zoomStep) == 'undefined') || (zoomStep < 5))
    {
      zoomStep = 5; // default
    }

    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();
    }

    // Google Analytics
    trackGA("NAVIGATION", "Zoom.In", "NA", 0);
  }

  function zoomOut()
  {
    drag = 1; // mtp: Requested by Chris

    // Just in case we're being called from display.php without these defaults,
    // check and default them here
    if ((typeof(minZoom) == 'undefined') || (minZoom < 5))
    {
      minZoom = 5; // default
    }
    if ((typeof(zoomStep) == 'undefined') || (zoomStep < 5))
    {
      zoomStep = 5; // default
    }
    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();
    }

    // Google Analytics
    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);
     
     /*
    $('imgload').src = firstimage.src;
    frameNumber = 0;					// FIXME

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

    repositionImage();
    anim_area.pan_on = true;
    */

    // 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)});
      }
    }
  }
  
//function toggleBtnHandler()
//{
//    alert ("Function button handler");
//} // functionButtonHandler

/*
  function show_hsinfo()
  {
    $('hsinfo').style.visibility = "visible";
  }

  function hide_hsinfo()
  {
    $('hsinfo').style.visibility = "hidden";
  }
*/
  

