// MOBOTIX Camera View Library
//
// Author: Daniel Kabs

/*
  Copyright (c) 2007, MOBOTIX AG, Kaiserslautern, Germany.

  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


// introducing namespace 'MX'

var MX = {
  version   : '1.0',
  author    : 'Daniel Kabs',
  copyright : 'MOBOTIX AG, Germany'
};

if (!("console" in window)) {
  console = new Object();
  console.log = console.debug = console.info = console.warn =
  console.error =  function() {  };
  console.error = alert;
}

/*
    ImageRefreshPeriodic object
    Periodically Refresh live image from camera

    Parameters to constructor function:
      ImageID           : ID of HTML Image element that needs to be refreshed
      RefreshRate       : update rate in seconds (minimum one second)

    Methods:
      getRefreshRate();
      setRefreshRate(value);
      stop();
*/

MX.ImageRefreshPeriodic = function(ImageID, RefreshRate) {
  // parameters
  if (!ImageID || RefreshRate < 1) {
    console.error("ImageRefreshPeriodic: Invalid constructor function call.");
  }
  // public methods
  this.getRefreshRate = function() {
    return RefreshRate;
  };
  this.setRefreshRate = function(NewRefreshRate) {
    if (NewRefreshRate >= 1) {
      RefreshRate = NewRefreshRate;
      if (SetTimeoutReference) {
        clearTimeout(SetTimeoutReference);
        loadNextImage();
      }
    }
  };
  this.stop = function() {
    aborted = true;
  };
  // private variables
  var ImgElement = document.getElementById(ImageID);
  var ImgSrc = ImgElement.src;
  var ImageBuffer = new Image();
  var LoadingStartTime = 0;
  var SetTimeoutReference = null;
  var aborted = false;
  // private methods
  var loadNextImage = function () {
    SetTimeoutReference = null;
    if (aborted) {
      return;
    }
    LoadingStartTime = new Date().getTime();
    ImageBuffer.src = MX.makeUncachedURL(ImgSrc);
  };
  var handleLoadEvent = function() {
    ImgElement.src = this.src;
    var WaitTime =  (RefreshRate * 1000) 
                  - ((new Date().getTime()) - LoadingStartTime);
                                               
    if (WaitTime < 0) {
      loadNextImage();
    } else {
      SetTimeoutReference = setTimeout(loadNextImage, WaitTime);
    }
  };
  var handleErrorEvent = function() {
    console.warn("Image load error:" + this.src);
    SetTimeoutReference = setTimeout(loadNextImage,
                                    (RefreshRate < 10 ? 10 : RefreshRate) * 1000);
  };
  var handleAbortEvent = function() {
    console.warn("Image loading aborted!");
  };
  // attach event handlers
  ImageBuffer.onload  = handleLoadEvent;
  ImageBuffer.onerror = handleErrorEvent;
  ImageBuffer.onabort = handleAbortEvent;
  // start refresh
  loadNextImage();
}; // end ImageRefreshPeriodic

MX.Urlcounter = Math.floor(Math.random() * 10000000);

MX.makeUncachedURL = function (path) {
  if (path.substr(-1,1) == "&") {
    ;
  } else if (path.indexOf("?") < 0) {
    path += "?";
  } else {
    path += "&";
  }
  return path + (MX.Urlcounter++);
};

MX.registerBodyOnloadHandler = function(onloadHandlerFunction) {
  if (typeof onloadHandlerFunction != 'undefined') {
    var oldOnloadHandlerFunction = window.onload;
    if (typeof(oldOnloadHandlerFunction) != 'function') {
      window.onload = onloadHandlerFunction;
    } else {
      window.onload = function() {
        oldOnloadHandlerFunction();
        onloadHandlerFunction();
      }
    }
  }
};

