
var currentIndex = 1;

function LayerImage(image, caption) {
  this.image = image;
  this.caption = caption;
}


function openImgLayer(productImages) {

  var imgLayer = document.getElementById("imglayer");
  var imgCaption = document.getElementById("imageCaption");
  var greyLayer = document.getElementById("ausgrauen");

  if (imgLayer && imgCaption) {

  var layerimage = document.getElementById("layerimage");
  if (layerimage) {
    layerimage.src = productImages[currentIndex].image.src;
  }

  setLayerProperties(productImages[currentIndex].image, imgLayer);
  setLayerCaption(productImages[currentIndex].caption, imgCaption );

  var imageCount = document.getElementById("imageCount");
  if (imageCount) {
    imageCount.innerHTML = "Bild " + (currentIndex+1) + " von " + productImages.length;
  }

  setLayerStyle(imgLayer, "block");
  setLayerStyle(greyLayer, "block");
  }

}

function setLayerCaption(caption, imgCaption) {
  var capDiv = document.getElementById(caption);
  if (capDiv) {
    imgCaption.innerHTML = capDiv.innerHTML;
  }
}


function nextImage() {
  if (productImages) {
    currentIndex++;
    currentIndex %= productImages.length;
    openImgLayer(productImages);
  }
}

function previousImage() {
  if (productImages) {
    currentIndex--;
    if (currentIndex < 0) currentIndex = productImages.length-1;
    openImgLayer(productImages);
  }
}


function setLayerProperties(layerimage, imgLayer) {

  var imgLayerHeight;
  var imgLayerWidth;

  if (layerimage.height > 0 && layerimage.width > 0) {
    imgLayerHeight = layerimage.height + 100;
    imgLayerWidth = layerimage.width + 40;
  }
  else {
    imgLayerHeight = 456 + 80;
    imgLayerWidth = 718 + 40;
  }

  var imgLayerPosX = "";

  if (window.innerWidth) {
    imgLayerPosX += (window.innerWidth - imgLayerWidth) / 2;
  }
  else {
    imgLayerPosX += (document.body.offsetWidth -imgLayerWidth) / 2;
  }
  imgLayerPosX += "px";

  var imgLayerPosY = "";
  if (window.innerHeight) {
    imgLayerPosY += window.innerHeight - 200 - imgLayerHeight;
  }
  else {
    imgLayerPosY += document.body.offsetHeight - imgLayerHeight - 300;    
  }
  imgLayerPosY +="px";

  imgLayer.style.left = imgLayerPosX;
  imgLayer.style.top =  imgLayerPosY;

  imgLayer.style.height = (imgLayerHeight + "px");
  imgLayer.style.width = (imgLayerWidth + "px");
}

function closeImgLayer() {
  var imgLayer = document.getElementById("imglayer");
  var greyLayer = document.getElementById("ausgrauen");
  setLayerStyle(imgLayer, "none");
  setLayerStyle(greyLayer, "none");
}

function setLayerStyle(layer, layerstyle) {
  if (layer) {
    layer.style.display = layerstyle;
  }
}
