// zoom.js, (C) Walter Bislin, Januar 2010
//
// description and download:
//  http://walter.bislins.ch/doku/zoom
//
// dependecies:
//  include: <script src="x.js" type="text/javascript"></script>
//  include: <script src="ic.js" type="text/javascript"></script>
//
// History:
//  06.01.2010: Renamed CLupe -> CZoom, CLupeObj -> Zoom, removed old stuff
//  24.11.2009: ZoomInit/Zoom.AutoPreload: Automatische Suche nach Zoombildern für das Preload.
//              ZoomDebug: Warnung, wenn gleiche ID in verschiedenen ZoomIn() verwendet wird.
//              Neu: NewWindowOnDblClick, ZoomWindowName, ZoomWindowFeatures
//  22.05.2009: ZoomInit( path, [ file1,...,fileN ] ) oder ZoomInit( url1,...,UrlN )
//  11.12.2008: EnableDblClick neu
//  15.08.2008: Relative und individuelle Positionierung des Zoombildes programmiert
//  29.01.2008: Problem mit IE6 behoben (Umlaute im Kommentaren können auf best. Servern Script korrumpieren!)
//  13.02.2007: Zoom-Source (small picture) no more limited to image type object
//              New properties AddPosX, AddPosY, ZIndex
//  15.02.2007: new function ZoomInit replaces ZoomHTML
//              ZoomInit can be placed anywhere on the page and can have a list of zoom pics to preload
//              ZoomInit sets up an onload-event (see xOnLoad) to create the html objects for the Zoom
//              new function ZoomPics replaces ZoomPreload
//              ZoomPics is usefull, if url's of zoom pics is not known yet on ZoomInit
//              ZoomPics can be placed anywhere. it installs an onload-event (see xOnLoad) handler to preload the zoom pics
//  23.12.2007: new function ZoomDebug
//              Self diagnosis implemented

// interface

var Zoom = null;

// new init functions
function ZoomInit() { 
//---------------------------------------------------change hier
//alert("zoominit");
Zoom.Init(ZoomInit.arguments); }
function ZoomPics() { Zoom.LoadPicsOnPageLoad(ZoomPics.arguments); }
function ZoomDebug() {
//---------------------------------------------------change hier
//alert("zoomdebug");
 Zoom.DebugOn = true; }

// zoom functions
function ZoomIn(aImgName,aBigImgUrl,aXOffset,aYOffset,aRelEleID) { Zoom.ZoomIn(aImgName,aBigImgUrl,aXOffset,aYOffset,aRelEleID); }
function ZoomOut() { Zoom.ZoomOut(); }
function ZoomEnable() { Zoom.Enable(); }
function ZoomDisable() { Zoom.Disable(); }

// implementation

// Zoom.State's
var CZHidden  = 0;
var CZLoading = 1;
var CZZoomIn  = 2;
var CZZoomed  = 3;
var CZZoomOut = 4;

function CZoom()
{
  if (Zoom) {return;} // only one instance allowed!
  // public properties
  this.DebugOn = false;
  this.AutoPreload = true;
  this.EnableInitOnClick = false;
  this.EnableDblClick = true;
  this.ZoomWindowName = 'Zoom';
  this.ZoomWindowFeatures = ''; // e.g: 'innerWidth=%w, innerHeight=%h';
  this.NewWindowOnDblClick = false;
  this.BorderColor = 'black';
  this.BorderWidth = 1;
  this.BaseZIndex = 1;
  this.ZIndex = 100;
  this.TimeSpan = 500;
  this.TimerInterval = 40; // 25 fps
  this.HideSmall = false; // to hide small image during zoom
  this.TimeModifyFunc = null;
  this.Enabled = true;
  this.VAlign = 'ToMiddle'; // Top, Middle, Bottom, ToMiddle, Relative
  this.HAlign = 'ToCenter'; // Left, Center, Right, ToCenter, Relative
  this.VMargin = 0;
  this.HMargin = 0;
  this.TargetOffsetX = 0;
  this.TargetOffsetY = 0;
  this.TargetElement = '';
  this.LoadText = 'Lade...';
  this.ErrorText = 'Zoom-Fehler!';
  this.ErrMsg = '';
  this.ZoomFunctionName = 'ZoomIn';
  // private properties
  this.AddPosX = 1; // position correcture of smallPos
  this.AddPosY = 1;
  this.SmallPosX = 0;
  this.SmallPosY = 0;
  this.SmallWidth = 0;
  this.SmallHeight = 0;
  this.BigPosX = 0;
  this.BigPosY = 0;
  this.BigWidth = 0;
  this.BigHeight = 0;
  this.CurrVAlign = this.VAlign;
  this.CurrHAlign = this.HAlign;
  this.CurrTargetEle = null;
  this.CurrTargetOffX = 0;
  this.CurrTargetOffY = 0;
  this.StartTime = 0;
  this.Timer = null;
  this.BigImgID = -1;
  this.SmallImg = null;
  this.WaitObj = null;
  this.ErrObj = null;
  this.ZoomImg = null;
  this.State = CZHidden;
  this.InitExecuted = false;
  this.PreloadExecuted = false;
  this.InitForced = false;
  this.HtmlWritten = false;
  this.DblClickActive = false;
  this.DebugDisplayed = false;
  Zoom = this;
}

CZoom.prototype.Init = function(aImgUrlList) {
  // syntax: Init( ['url1', 'url2', ...] ) or Init( ['path', [ 'file1', 'file2', ...]] )
  var me = this;
  function AfterPageLoad() {
    me.CreateHtmlObjects();
    if (aImgUrlList.length > 0) {
      me.Preload(aImgUrlList);
    }
    if (me.AutoPreload) {
      me.FindAndPreloadImages();
    }
    me.InitExecuted = true;
  }
  if (this.InitExecuted) {return;}
  xOnLoad(AfterPageLoad);
};

CZoom.prototype.ForceInit = function() {
  if (this.InitExecuted) {return;}
  this.CreateHtmlObjects();
  this.InitExecuted = true;
  this.InitForced = true;
};

CZoom.prototype.FindAndPreloadImages = function() {
  // searches for ZoomIn calls in all onclick handlers of all html elements of the page
  // and all href="javascript:ZoomIn..." in all A-tags of the page,
  // extracts the zoom images paths and pushes the paths to the preload list.
  var urlList = [];
  var callList = this.FindZoomFunctionCalls();
  for (var i = 0; i < callList.length; i++ ) {
    urlList.push( this.GetPathFromZoomFunctionCall(callList[i]) );
  }
  if (urlList.length > 0 ) { this.Preload(urlList); }
}

CZoom.prototype.FindZoomFunctionCalls = function() {
  // searches for ZoomIn calls in all onclick handlers of all html elements of the page
  // and all href="javascript:ZoomIn..." in all A-tags of the page,
  // and returns a string list of this calls.
  var callList = [];
  var el = xGetElementsByTagName( '*' );
  for (var i = 0; i < el.length; i++) {
    var e = el[i];
    // check onclick handlers of all html elements
    if (e.onclick) {
      var src = this.IsZoomFunctionCall(e.onclick);
      if (src != '') { callList.push(src); }
    }
    // check hrefs of all A-tags
    if (e.tagName && e.tagName.toLowerCase() == 'a') {
      var href = e.href || '';
      if (href.indexOf('javascript:') >= 0) {
        var src = this.IsZoomFunctionCall(href);
        if (src != '') { callList.push(src); }
      }
    }
  }
  return callList;
}

CZoom.prototype.HasMultipleCallsWithSameId = function() {
  // returns true if at least two ZoomIn calls woth same id's are found
  var lastId = '';
  var callList = this.FindZoomFunctionCalls();
  for (var i = 0; i < callList.length; i++ ) {
    var id = this.GetIdFromZoomFunctionCall(callList[i]);
    if (id == lastId) { return true; }
    lastId = id;
  }
  return false;
}

CZoom.prototype.IsZoomFunctionCall = function( aHandler ) {
  var s = '' + aHandler;
  var p = s.indexOf( this.ZoomFunctionName );
  return (p >= 0) ? s : '';
}

CZoom.prototype.GetPathFromZoomFunctionCall = function( aCallStr ) {
  var p = aCallStr.indexOf( this.ZoomFunctionName );
  if (p < 0) { return ''; }
  p = aCallStr.indexOf( ',', p );
  var sp = aCallStr.indexOf( '\'', p );
  var ep = aCallStr.indexOf( '\'', sp+1 );
  return aCallStr.substring( sp+1, ep );
}

CZoom.prototype.GetIdFromZoomFunctionCall = function( aCallStr ) {
  var p = aCallStr.indexOf( this.ZoomFunctionName );
  if (p < 0) { return ''; }
  p = aCallStr.indexOf( '(', p );
  var sp = aCallStr.indexOf( '\'', p );
  var ep = aCallStr.indexOf( '\'', sp+1 );
  return aCallStr.substring( sp+1, ep );
}

CZoom.prototype.LoadPicsOnPageLoad = function(aImgUrlList) {
  var me = this;
  function AfterPageLoad() {
    if (aImgUrlList.length > 0) {
      me.Preload(aImgUrlList);
    }
  }
  xOnLoad(AfterPageLoad);
};

CZoom.prototype.Preload = function(aImgUrlList) {
  // syntax: Preload( ['url1', 'url2', ...] ) or Preload( ['path', [ 'file1', 'file2', ...]] )
  if (aImgUrlList.length == 2 && typeof(aImgUrlList[1]) == 'object') {
    IC.PreloadImages( aImgUrlList[1], aImgUrlList[0] );
  }
  else {
    IC.PreloadImages( aImgUrlList );
  }
  this.PreloadExecuted = true;
};

CZoom.prototype.Diagnose = function() {
  var ics = IC.GetStatus();
  var s = '';
  if (this.ErrMsg != '') {
    s += 'Errors:\n';
    s += this.ErrMsg + '\n';
  }
  if (!this.PreloadExecuted) {
    s += 'Warning: No images preloaded!\nUse ZoomInit or ZoomPics to preload the zoom images or set Zoom.AutoPreload = true.';
    this.PreloadExecuted = true;
  }
  // check id's
  if (this.HasMultipleCallsWithSameId()) {
    s += 'Warning: Same id used in different calls of ZoomIn()!\nThis is commonly the cause for zooming in from the wrong thumbnail picture.';
  }
  if (s == '') {
    if (ics != '') {
      s = 'Zoom Status: ok.\nBut problems with some images detected.\nCheck url\'s in ZoomInit and ZoomIn!';
    }
  } else {
    s = 'Zoom Status:\n\n' + s;
  }
  if (ics != '') {
    s += '\n\nIC Status (IC = Image Caching and Preload):\n' + ics + '\n' + IC.ErrorMsg;
    IC.ResetStatus();
  }
  if (s != '' || !this.DebugDisplayed) {
    if (s == '') {s = 'Zoom Status: all fine!\n\nTo remove this message,\ndelete or comment the line with ZoomDebug(); from your script.';}
    alert( s );
  }
  this.ErrMsg = '';
  this.DebugDisplayed = true;
};

CZoom.prototype.AddError = function( aMsg ) {
  this.ErrMsg += aMsg + '\n';
};

CZoom.prototype.CreateHtmlObjects = function()
{
  var me = this;
  var msgFailed = 'CZoom.CreateHtmlObjects: creating Zoom HTML failed ';
  function OnClick() { me.ZoomOut(); }
  function OnDblClick() { me.NewWindow(); }
  var oImg = xCreateElement('img');
  if (!oImg || !oImg.style) {
    this.AddError( msgFailed + '(xCreateElement)' );
    return;
  }
  oImg.id = 'ZoomPic';
  oImg.style.position = 'absolute';
  oImg.style.visibility = 'hidden';
  oImg.style.zIndex = this.ZIndex;
  if (this.BorderWidth > 0) {
    oImg.style.border = this.BorderWidth+'px solid '+this.BorderColor;
  }
  oImg.onclick = OnClick;
  if (this.EnableDblClick) {
    oImg.ondblclick = OnDblClick;
  }
  var oDivWait = xCreateElement('div');
  var oDivError = xCreateElement('div');
  var oTextWait = xCreateTextNode(this.LoadText);
  var oTextError = xCreateTextNode(this.ErrorText);
  if (!oDivWait || !oDivError || !oTextWait || !oTextError) {
    this.AddError( msgFailed + '(xCreateTextNode)' );
    return;
  }
  xAppendChild(oDivWait,oTextWait);
  xAppendChild(oDivError,oTextError);
  oDivWait.id = 'ZoomPicWait';
  oDivWait.style.position = 'absolute';
  oDivWait.style.visibility = 'hidden';
  oDivWait.style.zIndex = this.BaseZIndex + 1;
  oDivWait.style.backgroundColor = 'white';
  oDivWait.style.color = 'black';
  oDivWait.style.padding = '0 4px';
  oDivWait.style.fontSize = '10pt';
  oDivWait.style.border = '1px solid black';
  //
  oDivError.id = 'ZoomPicError';
  oDivError.style.position = 'absolute';
  oDivError.style.visibility = 'hidden';
  oDivError.style.zIndex = this.BaseZIndex + 1;
  oDivError.style.backgroundColor = 'white';
  oDivError.style.color = 'black';
  oDivError.style.padding = '0 4px';
  oDivError.style.fontSize = '10pt';
  oDivError.style.border = '1px solid black';
  // Objekte als erste in body einfuegen
  var oElements = xGetElementsByTagName('body');
  if (!oElements || oElements.length < 1) {
    this.AddError( msgFailed + '(no body tag found)' );
    return;
  }
  var oBody = oElements[0];
  if (!xHasChildNodes(oBody)) {
    this.AddError( msgFailed + '(no html elements in body tag found)' );
    return;
  }
  oElements = xChildNodes(oBody);
  xInsertBefore(oBody,oDivError,oElements[0]);
  xInsertBefore(oBody,oDivWait,oDivError);
  xInsertBefore(oBody,oImg,oDivWait);
  this.WaitObj = oDivWait;
  this.ErrObj = oDivError;
  this.ZoomImg = oImg;
  this.HtmlWritten = true;
};

CZoom.prototype.ZoomIn = function(aImgName, aBigImgUrl, aXOffset, aYOffset, aRelEleID )
{
  // fallback when xOnLoad failed:
  if (!this.InitExecuted) {
    if (this.EnableInitOnClick) {
      this.AddError( 'CZoomIn: Zoom not initialized - forcing init now!\nCheck ZoomInit and ensure no onload is in body tag!' );
      this.ForceInit();
      if (!this.HtmlWritten) {
        this.AddError( 'CZoomIn: forced Init failed, give up here.' );
        return;
      }
    } else {
      if (this.DebugOn) {
        this.AddError( 'CZoomIn: Zoom not initialized!\nCheck ZoomInit and ensure no onload is in body tag\nor set Zoom.EnableInitOnClick = true;' );
        this.Diagnose();
      }
      return;
    }
  }
  if (this.DebugOn) {this.Diagnose();}
  if (!this.Enabled) {return;}
  if (!this.WaitObj) {this.WaitObj = xGetElementById('ZoomPicWait');}
  if (!this.ErrObj)  {this.ErrObj  = xGetElementById('ZoomPicError');}
  if (!this.ZoomImg) {this.ZoomImg = xGetElementById('ZoomPic');}
  var bigImgID = IC.FindImage(aBigImgUrl);

  // cancel zoom shortly after doubleclick to prevent double zoom
  if (this.EnableDblClick && this.DblClickActive) { return; }

  // init current target position and alignment
  this.CurrVAlign = this.VAlign;
  this.CurrHAlign = this.HAlign;
  this.CurrTargetEle = null;
  this.CurrTargetOffX = this.TargetOffsetX;
  this.CurrTargetOffY = this.TargetOffsetY;
  if (this.TargetElement != '') {
    var relEle = xGetElementById(this.TargetElement);
    if (relEle) {
      this.CurrTargetEle = relEle;
    }
  }
  // overwrite global settings with local arguments
  if (xNum(aXOffset) || xNum(aYOffset) || xStr(aRelEleID)) {
    this.CurrVAlign = 'Relative';
    this.CurrHAlign = 'Relative';
    this.CurrTargetEle = null;
    this.CurrTargetOffX = 0;
    this.CurrTargetOffY = 0;
  }
  if (xNum(aXOffset)) {this.CurrTargetOffX = aXOffset;}
  if (xNum(aYOffset)) {this.CurrTargetOffY = aYOffset;}
  if (xStr(aRelEleID)) {
    var relEle = xGetElementById(aRelEleID);
    if (relEle) {this.CurrTargetEle = relEle;}
  }

  if ((this.State != CZHidden) && (bigImgID != -1) && (bigImgID == this.BigImgID)) {
    if (this.State == CZLoading) {
      xHide( this.WaitObj );
      xHide( this.ErrObj );
      this.State = CZHidden;
      return;
    }
    if (this.State == CZZoomIn || this.State == CZZoomed) {
      this.ZoomOut();
      return;
    }
    // this.State == CZZoomOut
    if (this.Timer) {
      clearTimeout( this.Timer );
      this.Timer = null;
    }
    this.StartTime = xTimeMS() - this.TimeSpan + (xTimeMS() - this.StartTime);
    this.State = CZZoomIn;
    var me = this; // closure -> http://walter.bislins.ch/lexi/closure.html
    this.Timer = setTimeout(function(){me.Enlarge();}, this.TimerInterval);
    return;
  }

  if (this.State == CZLoading) {
    xHide( this.WaitObj );
    xHide( this.ErrObj );
    this.State = CZHidden;
  }
  else if (this.State != CZHidden) {
    if (this.Timer) {
      clearTimeout( this.Timer );
      this.Timer = null;
    }
    this.HideZoomImg();
  }
  this.SmallImg = xGetElementById(aImgName);
  if ((bigImgID != -1) && IC.IsLoaded(bigImgID)) {
    this.BigImgID = bigImgID;
    this.StartZoom();
  }
  else {
    this.GetSmallImgData();
    var y = (this.SmallHeight - xHeight(this.WaitObj) - 5);
    xMoveTo( this.WaitObj, this.SmallPosX+3, this.SmallPosY+y );
    xMoveTo( this.ErrObj, this.SmallPosX+3, this.SmallPosY+y );
    xShow( this.WaitObj );
    this.State = CZLoading;
    var me = this;
    this.BigImgID = IC.LoadImage( aBigImgUrl, function(aImgID){me.OnLoad(aImgID);} );
  }
};

CZoom.prototype.Enable = function() { this.Enabled = true; };
CZoom.prototype.Disable = function() { this.Enabled = false; };

CZoom.prototype.GetSmallImgData = function()
{
  this.SmallWidth = xWidth(this.SmallImg) + 2*this.BorderWidth;
  this.SmallHeight = xHeight(this.SmallImg) + 2*this.BorderWidth;
  this.SmallPosX = xPageX(this.SmallImg) + (xWidth(this.SmallImg)-this.SmallWidth)/2 + this.AddPosX; // Raender beruecksichtigen
  this.SmallPosY = xPageY(this.SmallImg) + (xHeight(this.SmallImg)-this.SmallHeight)/2 + this.AddPosY;
};

CZoom.prototype.OnLoad = function( aImgID )
{
  if ((this.State == CZLoading) && (this.BigImgID == aImgID)) {
    var imgState = IC.Image(aImgID).CacheState;
    if (imgState == ICLoaded) {
      this.StartZoom();
    }
    else if (imgState == ICError || imgState == ICAbort) {
      this.State = CZHidden;
      xHide( this.WaitObj );
      xShow( this.ErrObj );
      var me = this; // closure -> http://walter.bislins.ch/lexi/closure.html
      setTimeout(function(){xHide(me.ErrObj);}, 2500);
    }
  }
};

CZoom.prototype.Range = function( aValue, aMin, aMax ) {
  return aMin + (aMax-aMin)*aValue;
};

CZoom.prototype.StartZoom = function()
{
  this.BigImg = IC.Image(this.BigImgID);
  this.ZoomImg.src = this.BigImg.src;
  this.GetSmallImgData();
  this.BigWidth = this.BigImg.width + 2*this.BorderWidth;
  this.BigHeight = this.BigImg.height + 2*this.BorderWidth;
  if ((this.SmallWidth >= this.BigWidth) || (this.SmallHeight >= this.BigHeight)) {return;}
  // assert: this.BigImg is greater than this.SmallImg

  var clW = xClientWidth();
  var clX = xScrollLeft();
  if (this.CurrHAlign == 'Left') {
    this.BigPosX = this.HMargin;
    // move big image into client range
    if ((this.BigPosX+this.BigWidth) > (clX+clW)) {this.BigPosX = (clX+clW) - this.BigWidth;}
    if ((this.BigPosX)               < (clX)    ) {this.BigPosX =  clX;}
  } else if (this.CurrHAlign == 'Right') {
    this.BigPosX = (clX+clW) - this.BigWidth - this.HMargin;
    // move big image into client range
    if ((this.BigPosX) < (clX)) {this.BigPosX =  clX;}
  } else if (this.CurrHAlign == 'Relative') {
    var ref = this.SmallImg;
    if (this.CurrTargetEle) {ref = this.CurrTargetEle;}
    this.BigPosX = xPageX(ref) + this.CurrTargetOffX;
  } else {
    // compute big position: move big image according to its size rel. to the windows range
    // to the center of the windows range (client range). As smaller the image, as farther away
    // from the center.
    var dxCenter = 1;
    if (this.BigWidth <= clW) {
      // assert: this.BigImg width full inside client range
      dxCenter = (this.BigWidth-this.SmallWidth)/(clW-this.SmallWidth);
      if (dxCenter < 0) {dxCenter = 0;}
    }
    if (this.CurrHAlign == 'Center') {dxCenter = 1;}
    var cxBig = clW / 2;
    var cxSmall = this.SmallPosX-clX + (this.SmallWidth/2);
    var cx = dxCenter*(cxBig-cxSmall)+cxSmall;
    this.BigPosX = clX + cx - this.BigWidth/2;
    if (this.BigPosX < 0) {this.BigPosX = 0;}
    if (this.BigWidth <= clW) {
      // move big image into client range
      if ((this.BigPosX+this.BigWidth) > (clX+clW)) {this.BigPosX = (clX+clW) - this.BigWidth;}
      if ((this.BigPosX)               < (clX)    ) {this.BigPosX =  clX;}
    }
  }
  var clH = xClientHeight();
  var clY = xScrollTop();
  if (this.CurrVAlign == 'Top') {
    this.BigPosY = this.VMargin;
    // move big image into client range
    if ((this.BigPosY+this.BigHeight) > (clY+clH)) {this.BigPosY = (clY+clH) - this.BigHeight;}
    if ((this.BigPosY)                < (clY)    ) {this.BigPosY =  clY;}
  } else if (this.CurrVAlign == 'Bottom') {
    this.BigPosY = (clY+clH) - this.BigHeight - this.VMargin;
    // move big image into client range
    if ((this.BigPosY) < (clY)) {this.BigPosY =  clY;}
  } else if (this.CurrVAlign == 'Relative') {
    var ref = this.SmallImg;
    if (this.CurrTargetEle) {ref = this.CurrTargetEle;}
    this.BigPosY = xPageY(ref) + this.CurrTargetOffY;
  } else {
    var dyCenter = 1;
    if (this.BigHeight <= clH) {
      // assert: this.BigImg height full inside client range
      dyCenter = (this.BigHeight-this.SmallHeight)/(clH-this.SmallHeight);
      if (dyCenter < 0) {dyCenter = 0;}
    }
    if (this.CurrVAlign == 'Middle') {dyCenter = 1;}
    var cyBig = clH / 2;
    var cySmall = this.SmallPosY-clY + (this.SmallHeight/2);
    var cy = dyCenter*(cyBig-cySmall)+cySmall;
    this.BigPosY = clY + cy - this.BigHeight/2;
    if (this.BigPosY < 0) {this.BigPosY = 0;}
    if (this.BigHeight <= clH) {
      // move big image into client range
      if ((this.BigPosY+this.BigHeight) > (clY+clH)) {this.BigPosY = (clY+clH) - this.BigHeight;}
      if ((this.BigPosY)                < (clY)    ) {this.BigPosY =  clY;}
    }
  }
  this.StartTime = xTimeMS();
  var me = this; // closure -> http://walter.bislins.ch/lexi/closure.html
  this.Timer = setTimeout(function(){me.Enlarge();}, this.TimerInterval);
};

CZoom.prototype.Enlarge = function()
{
  if (this.Timer) {
    clearTimeout(this.Timer);
    this.Timer = null;
  }
  if (this.DblClickActive) { return; }
  var param = (xTimeMS() - this.StartTime) / this.TimeSpan;
  var eom = param >= 1;
  if (param > 1) {param = 1;}
  if (this.TimeModifyFunc) {param = this.TimeModifyFunc(param);}
  if (param < 0) {param = 0;}
  if (param > 1) {param = 1;}
  var x = this.Range( param, this.SmallPosX, this.BigPosX );
  var y = this.Range( param, this.SmallPosY, this.BigPosY );
  var w = this.Range( param, this.SmallWidth, this.BigWidth );
  var h = this.Range( param, this.SmallHeight, this.BigHeight );
  xMoveTo( this.ZoomImg, x, y );
  xResizeTo( this.ZoomImg, w, h );
  if (this.State != CZZoomIn) {
    xHide( this.WaitObj );
    xHide( this.ErrObj );
    xShow( this.ZoomImg );
    if (this.HideSmall) {xHide( this.SmallImg );}
    this.State = CZZoomIn;
  }
  var me = this;
  if (eom)
  {
    this.State = CZZoomed;
    this.Timer = setTimeout(function(){me.CheckOutOfWindow();}, 200);
  }
  else
  {
    this.Timer = setTimeout(function(){me.Enlarge();}, this.TimerInterval);
  }
};

CZoom.prototype.CheckOutOfWindow = function()
{
  var space = (xClientHeight()-this.BigHeight) / 2;
  var newY = xScrollTop() + space;
  var toleranz;
  if (space > 0) {
    toleranz = space + (this.BigHeight * 2 / 3);
  } else {
    toleranz = -space + (xClientHeight() * 2 / 3);
  }
  if (Math.abs(newY-this.BigPosY) > toleranz) {
    this.ZoomOut();
    return;
  }
  var me = this;
  this.Timer = setTimeout(function(){me.CheckOutOfWindow();}, 200);
};

CZoom.prototype.NewWindow = function()
{
  function CancelDblClick() {
    me.DblClickActive = false;
  }
  if (!this.HtmlWritten) {return;}
  // prevent zoom on double click
  var me = this;
  if (!this.DblClickActive) {
    this.DblClickActive = true;
    setTimeout( function(){ CancelDblClick(); }, 500 );
  }
  if (this.HideSmall) {xShow( this.SmallImg );}
  xHide( this.ZoomImg );
  xMoveTo( this.ZoomImg, 0, 0 );
  xResizeTo( this.ZoomImg, 0, 0 );
  this.State = CZHidden;
  if (this.NewWindowOnDblClick) {
    var features = this.ZoomWindowFeatures;
    features = features.replace( /%w/gi, this.BigWidth.toString() );
    features = features.replace( /%h/gi, this.BigHeight.toString() );
    var w = window.open( IC.ImageUrl(this.BigImgID), this.ZoomWindowName, features );
  } else {
    location.href = IC.ImageUrl(this.BigImgID);
  }
};

CZoom.prototype.ZoomOut = function()
{
  if (!this.HtmlWritten) {return;}
  if (this.State == CZHidden || this.State == CZZoomOut) {return;}
  if (this.State == CZLoading) {
    xHide( this.WaitObj );
    xHide( this.ErrObj );
    this.State = CZHidden;
    return;
  }
  if (this.Timer) {
    clearTimeout(this.Timer);
    this.Timer = null;
  }
  this.SmallPosX = xPageX(this.SmallImg) + (xWidth(this.SmallImg)-this.SmallWidth)/2 + this.AddPosX; // Raender beruecksichtigen
  this.SmallPosY = xPageY(this.SmallImg) + (xHeight(this.SmallImg)-this.SmallHeight)/2 + this.AddPosY;
  if (this.State == CZZoomIn) {
    this.StartTime = xTimeMS() - this.TimeSpan + (xTimeMS() - this.StartTime);
  } else {
    this.StartTime = xTimeMS();
  }
  this.State = CZZoomOut;
  var me = this; // closure -> http://walter.bislins.ch/lexi/closure.html
  this.Timer = setTimeout(function(){me.Shrink();}, this.TimerInterval);
};

CZoom.prototype.HideZoomImg = function()
{
  if (this.HideSmall) {xShow( this.SmallImg );}
  xHide( this.ZoomImg );
  xMoveTo( this.ZoomImg, 0, 0 );
  xResizeTo( this.ZoomImg, 0, 0 );
  this.State = CZHidden;
};

CZoom.prototype.Shrink = function()
{
  if (this.Timer) {
    clearTimeout(this.Timer);
    this.Timer = null;
  }
  var param = (xTimeMS() - this.StartTime) / this.TimeSpan;
  var eom = param >= 1;
  if (param > 1) {param = 1;}
  if (this.TimeModifyFunc) {param = this.TimeModifyFunc(param);}
  if (param < 0) {param = 0;}
  if (param > 1) {param = 1;}
  var x = this.Range( param, this.BigPosX, this.SmallPosX );
  var y = this.Range( param, this.BigPosY, this.SmallPosY );
  var w = this.Range( param, this.BigWidth, this.SmallWidth );
  var h = this.Range( param, this.BigHeight, this.SmallHeight );
  xMoveTo( this.ZoomImg, x, y );
  xResizeTo( this.ZoomImg, w, h );
  if (eom)
  {
    this.HideZoomImg();
  }
  else
  {
    xMoveTo( this.ZoomImg, x, y );
    xResizeTo( this.ZoomImg, w, h );
    var me = this; // closure -> http://walter.bislins.ch/lexi/closure.html
    this.Timer = setTimeout(function(){me.Shrink();}, this.TimerInterval);
  }
};

Zoom = new CZoom();

Zoom.TimeModifyFunc = function( aValue ) { return (0.5 - 0.5 * Math.cos(Math.PI*aValue)); };

