// #################################################################
// ################   CAROUSEL TEASER  FUNCTIONS   #################
// #################################################################
var CarouselDuration = false;
var actPos=1;
var maxPos=10;
function moveCarousel(teaserId, dir, imgCount, imgSize, imgTotal) {
 try {
 updateIVW(document.location.pathname + '/slider');
 if (!imgCount) {imgCount = 3}
 if (!imgSize) {imgSize = 160} // ImageSize incl Padding
 imgSize = imgCount * imgSize;
 var carousel = $(teaserId);
 var carouselControl = $(teaserId+'Controls');
// var imgTotal = (carousel.childElements()).length - 2;
 if (!imgTotal) {
   imgTotal = 0;
   carousel.childElements().each(function(element) {
     if (element.className.indexOf('single') >= 0) ++imgTotal;
   });
 }
 carousel.setStyle({
   width: (Math.ceil(imgTotal/imgCount) * imgSize) +'px'
 });
 actPos = Position.positionedOffset(carousel)[0];
 maxPos = ((Math.ceil((imgTotal)/imgCount) * imgSize)-imgSize) * -1;
 if (dir =="right") {
  if ((actPos <= maxPos) && !CarouselDuration) {
    new Effect.Move(carousel, {
    x: 0, y: 0, mode: 'absolute',
    beforeStart:function(){CarouselDuration=true},
    afterFinish:function(){CarouselDuration=false}
    });
    new Effect.Move(carouselControl, {
    x: 0, y: 0, mode: 'absolute'
    });    
  }
  if ((actPos > maxPos) && !CarouselDuration) {
    new Effect.Move(carousel, {
    x: (imgSize * -1), y: 0, mode: 'relative',
    beforeStart:function(){CarouselDuration=true},
    afterFinish:function(){
        CarouselDuration=false;
        if ($(teaserId + 'Num'))
          $(teaserId + 'Num').update(parseInt($(teaserId + 'Num').innerHTML)+1);}
    });
    new Effect.Move(carouselControl, {
    x: 18, y: 0, mode: 'relative'
    });
  }
 } else if (dir =="left") {
  if ((actPos >= 0) && !CarouselDuration) {
    new Effect.Move(carousel, {
    x: maxPos, y: 0, mode: 'absolute',
    beforeStart:function(){CarouselDuration=true},
    afterFinish:function(){CarouselDuration=false}
    });
    new Effect.Move(carouselControl, {
    x: 0, y: 0, mode: 'absolute'
    });    
  }
  if ((actPos < 0) && !CarouselDuration) {
   new Effect.Move(carousel, {
    x: imgSize, y: 0, mode: 'relative',
    beforeStart:function(){CarouselDuration=true},
    afterFinish:function(){
      CarouselDuration=false;
      if ($(teaserId + 'Num'))
        $(teaserId + 'Num').update(parseInt($(teaserId + 'Num').innerHTML)-1);}
    });
    new Effect.Move(carouselControl, {
    x: -18, y: 0, mode: 'relative'
    });
  }

 } else {
  if (!CarouselDuration) {
    new Effect.Move(carousel, {
    x: (dir*imgSize)*-1, y: 0, mode: 'absolute',
    beforeStart:function(){CarouselDuration=true},
    afterFinish:function(){CarouselDuration=false}
    });
    new Effect.Move(carouselControl, {
    x: (dir*18), y: 0, mode: 'absolute'
    });
  }
 }
 } catch(e) {}
}


// #################################################################
// ################   HELPER           FUNCTIONS   #################
// #################################################################
  /**
   * Needed for the NewsletterAbo Teaser
   */
  function refreshNewsletterMessage(request, json)
  {
    if (json.success) {
      $('nlEmail').addClassName('ugen');
      $('nlEmail').value = json.message;
      $('newsLetterAboMessage').update('');
    }
    else {
      $('newsLetterAboMessage').update(json.message);
    }
  }

  function gotoUrl(url) {
    window.location.href = url;
  }

/*Zusatzfunktion Elemente anhand von Klassen identifizieren*/
  function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();
    if ( node == null )
      node = document;
    if ( tag == null )
      tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\\\s)"+searchClass+"(\\\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
      if ( pattern.test(els[i].className) ) {
        classElements[j] = els[i];
        j++;
      }
    }
    return classElements;
  }

/*Eine ganze Box mit einem Link belegen*/
  function openLink(o) {
    var links = o.getElementsByTagName("a");
    var link = links[0];
    if(!link.onclick) {
      var href = link.href;
      if (href.substr(0, 11) == 'javascript:' ) {
        // give control to the inline javascript
        eval(unescape(href.substr(11)));
      } else {
        var target_host = href.match(/^[^\.]*\/([^/]*)\/.*/)[1];
        // open link in new window if it targets to a different hostname
        if (window.location.hostname == target_host) {
          location.href=link.href;
        } else {
          window.open(link.href);
        }
      }
      // prevent execution of the non-javascript-link (repeated in template,
      // don't know why it's neccessary two times).
      return false;
    } else {
      link.onclick();
    }
  }

/*Klasse 'hi' setzen*/
  function highlight(which) {
    if (which.className != "hi") {
      which.className = "hi";
    }
    else {
      which.className = "";
    }
  }

/*Klasse 'hi' setzen*/
  function high(which) {
    if (which.className != "hi") {
      which.className = "hi";
    }
    else {
      which.className = "";
    }
  }

/*Inputs leeren*/
  function clearInput(what, where) {
    if(where.value == what) where.value = "";
    else where.select();
  }

  function fillInput(what, where) {
    if(where.value == "") where.value = what;
  }

/*Dots Layer setzen (Bulletpoints)*/
  function spelarlite(dotA) {
    var venten = dotA.id.slice(4, 6);
    var bh = document.getElementById("sitter" + venten);
    var allLayers = getElementsByClass("dotLayer");
    if (bh.style.display != "block") {
      for (bot = 0; bot < allLayers.length; bot++) {
        allLayers[bot].style.display = "none";
      }
      bh.style.display = "block";
    }
    else
      bh.style.display = "none";
  }

  function closeLayer(which) {
    which.parentNode.style.display = "none";
  }

/*Dots ein- und ausschalten*/
  function toggleDots(what) {
    var allDots = getElementsByClass("dot");
    if (allDots[0].style.display != "none") {
      for (d = 0; d < allDots.length; d++) {
        allDots[d].style.display = "none";
      }
      what.innerHTML = "Bild mit Punkten ansehen";
    }
    else {
      for (d = 0; d < allDots.length; d++) {
        allDots[d].style.display = "block";
      }
      what.innerHTML = "Bild ohne Punkte ansehen";
    }
  }

/*Show Help*/
  function showHelp(number) {
    if (document.getElementById("infoBox"+number).style.display != "block")
    document.getElementById("infoBox"+number).style.display = "block";
    else document.getElementById("infoBox"+number).style.display = "none";
  }

/*Inline Galery*/
  var index = 0;
  function switchImgs(count, dir, slideGallery) {
    if (CarouselDuration) return false;

    var src = ""; width = ""; height = "";

    if (dir == "nexx") {
      if ((index+1) <= (count-1)) {
        src = aImages[index+1]["src"];
        $("prev").show();
        changeCredits(aImages[index+1]["credits"]);
        changeHeadline(aImages[index+1]["headline"]);
        changeText(aImages[index+1]["text"]);
        changeShowBigImageLink(count,(index+1));
        changeSupplier(aImages[index+1]["supplier_id"]);
        changeImageCounter(aImages[index+1]["counter"]);
        if (slideGallery) fadeSmallImages(count,index+1);
      }
      if ((index+1) == (count-1)) {
        $("nexx").hide();
      }
      index++;
      if ((index+1) >= count) index = count-1;
    } else if (dir == "prev") {
      if ((index-1) >= 0) {
        src = aImages[index-1]["src"];
        $("nexx").show();
        changeCredits(aImages[index-1]["credits"]);
        changeHeadline(aImages[index-1]["headline"]);
        changeText(aImages[index-1]["text"]);
        changeShowBigImageLink(count,(index-1));
        changeSupplier(aImages[index-1]["supplier_id"]);
        changeImageCounter(aImages[index-1]["counter"]);
        if (slideGallery) fadeSmallImages(count,index-1);
      }
      if ((index-1) == 0) {
        $("prev").hide();
      }
      index--;
      if (index <= 0) index = 0;
    }

    if (slideGallery) {
      if (slideGallery == "left" && (index-1 > 0) && ((index) % 10 == 0 )) {
        moveCarousel('carousel', slideGallery,10,71);
      } else if (slideGallery == "right" && ((index+1) < count) && (index != 0) && ((index+1) % 10 == 0 )) {
        moveCarousel('carousel', slideGallery,10,71);
      }
    }

    if ($("prev") && $("nexx")) {
      if (slideGallery) {
        $("prev").style.top = "256px";
        $("nexx").style.top = "256px";
      } else {
        $("prev").style.top = aImages[index]['height'] / 2 - 24 + "px";
        $("nexx").style.top = aImages[index]['height'] / 2 - 24 + "px";
      }
    }

    showImg(src);

  }


  function showImg(new_img_src){
   var myImage = new Image();
   myImage.src = new_img_src;
   $("galleryImage").src = "";
   $("galleryImage").src = myImage.src;
  }

  /**
   * shows the image in the bigGallery if you click the slide buttons. Jumps +10 Or -10 images
   */
  function switchSlideImgs(count, dir, slideGallery, fromSlide) {
    if (CarouselDuration) return false;
    if (fromSlide) {
      if (slideGallery == "left") {
        index = index - 10;
        if (index < 0) index = 0;
      } else if (slideGallery == "right") {
        index = index + 10;
        if ((index+1) >= count) index = count-1;
      }
    }
    $("galleryImage").src = aImages[index]["src"];
    changeCredits(aImages[index]["credits"]);
    fadeSmallImages(count,index);
  }

  /**
   * fades the actual image out in the sildegallery
   *
   * @param  int count
   * @param  i actual image index
   * @return -
   */
  function fadeSmallImages(count,index) {
    // fade all other images in
    for (j=0;j<count;j++) {
      if ($('smallImageDiv_'+j)) {
        //Effect.Fade($('smallImage_'+j),{duration: 0, from: 0.4, to:1})
        $('smallImageDiv_'+j).style.border = "1px solid #ECE8E3"
      }
    }
    // fade the actual image out
    if ($('smallImageDiv_'+index)) {
      //Effect.Fade($('smallImage_'+index),{duration: 0.1, from: 1, to:0.4});
      $('smallImageDiv_'+index).style.border = "1px solid #8C002B"
    }
  }

  /**
   * Shows the correct "show-big-image-link" under an image
   * @param  int count
   * @param  index actual image index
   */
  function changeShowBigImageLink(count, index) {
    for (i = 0; i < count; i++) {
      if ($('showBigImgLink_'+i)) {
        $('showBigImgLink_'+i).style.display = "none";
      }
    }
    if ($('showBigImgLink_'+index)) {
      $('showBigImgLink_'+index).style.display = "inline";
    }
  }

  /**
   * Changes the supplier
   * @param string
   */
  function changeSupplier(supplier) {
    if ($("supplier_"+supplier)) {
      $('supplier_container').innerHTML = $('supplier_'+supplier).innerHTML;
    }
  }

  /**
   * Changes the image text
   * @param string
   */
  function changeText(text) {
    if ($("image_text")) {
      $("image_text").innerHTML = text;
    }
  }

  /**
   * Changes the image headline
   * @param string
   */
  function changeHeadline(headline) {
    if ($("sidebar_h3")) {
      $("sidebar_h3").innerHTML = headline;
    }
  }


  /**
   * Adds the credit info under in image
   * @param string
   */
  function changeCredits(credits) {
    if (credits) {
      $("creditsSpan").innerHTML = "Fotos: " + credits;
      $("creditsSpan").show();
    } else {
      $("creditsSpan").hide();
      $("creditsSpan").innerHTML = "";
    }
  }

  /**
   * Changes the image counter
   * @param string
   */
  function changeImageCounter(text) {
    if ($("imagecounter")) {
      $("imagecounter").innerHTML = text;
    }
  }

  /**
   * Toggles the navigation-arrows on an image
   * @param  int count
   * @param  string - shows the navigation or hides it
   */
  var nexxFade = false;
  var prevFade = false;
  function toggleGalleryNavigation(count, display) {
    if (display == "show") {
      clearTimeout(aktiv);

      //if (nexxFade && prevFade) {
      //  nexxFade.cancel();
      //  prevFade.cancel();
      //}
      //$("nexx").setOpacity(1);
      //$("prev").setOpacity(1);

      if (index != (count-1)) {
        $("nexx").show();
      } else {
        $("nexx").hide();
      }
      if (index != 0) {
        $("prev").show();
      } else {
        $("prev").hide();
      }
    } else {
       // nexxFade = Effect.Fade($("nexx"),{duration: 0.8, from: 1, to:0});
       // prevFade = Effect.Fade($("prev"),{duration: 0.8, from: 1, to:0});
       $("nexx").hide();
       $("prev").hide();
    }
  }

  /**
   * Hides the navigation for the inline gallery
   */
  function hideGalleryNavigation() {
    $("nexx").hide();
    $("prev").hide();
  }

  /**
   * Shows the gallery image
   * @param  int count
   * @param  index actual image index
   */
  function showGalleryImage(count,i) {
    index = i;
    $("galleryImage").src = aImages[i]["src"];
    fadeSmallImages(count,i);
    toggleGalleryNavigation(count,"show");
    changeHeadline(aImages[i]["headline"]);
    changeText(aImages[i]["text"]);
    changeCredits(aImages[i]["credits"]);
    if ($("prev") && $("nexx")) {
      $("prev").style.top = "256px";
      $("nexx").style.top = "256px";
    }
  }

  /**
   * Adds the credit info under in image
   * @param string
   */
  function changeShopCredits(credits) {
    if (credits) {
      $("creditsSpan").innerHTML = "Fotos: " + credits;
      $("creditsDivShop").show();
    } else {
      $("creditsDivShop").hide();
      $("creditsSpan").innerHTML = "";
    }
  }

  /**
   * Shows the big image
   * @param  int count
   * @param  index actual image index
   */
  function showBigImage(count,index) {
    $("galleryImage").src = aImages[index]["src"];
    changeShowBigImageLink(count, index);
    changeHeadline(aImages[index]["headline"]);
    changeText(aImages[index]["text"]);
    changeShopCredits(aImages[index]["credits"]);
    for (i=0;i<count;i++) {
      $('smallImage_'+i).className = "";
    }
    $('smallImage_'+index).className = "active";
  }


// #################################################################
// ################   Global - funktions   #########################
// #################################################################


function submitVoteForm(target) {
   win = window.open('',target,"width=600,height=550,toolbars=0,resizable=0");
   win.focus();
   return true;
}

String.prototype.trim = function() {
  return(this.replace(/^[\s\n]+/,'').replace(/[\s\n]+$/,''));
}

/**
 * DESCRIPTION: Helper function to get page height and width
 *
 * @return Array[pageWidth, pageHeight, windowWidth, windowHeight]
 */
function getPageSize(){
  var xScroll, yScroll;
  if (window.innerHeight && window.scrollMaxY) {
  xScroll = document.body.scrollWidth;
  yScroll = window.innerHeight + window.scrollMaxY;
  }
  else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
  xScroll = document.body.scrollWidth;
  yScroll = document.body.scrollHeight;
  }
  else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
  xScroll = document.body.offsetWidth;
  yScroll = document.body.offsetHeight;
  }
  var windowWidth, windowHeight;
  if (self.innerHeight) {	// all except Explorer
  windowWidth = self.innerWidth;
  windowHeight = self.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
  windowWidth = document.documentElement.clientWidth;
  windowHeight = document.documentElement.clientHeight;
  }
  else if (document.body) { // other Explorers
  windowWidth = document.body.clientWidth;
  windowHeight = document.body.clientHeight;
  }
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
  pageHeight = windowHeight;
  }
  else {
  pageHeight = yScroll;
  }
  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){
  pageWidth = windowWidth;
  }
  else {
  pageWidth = xScroll;
  }
  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
  return arrayPageSize;
}

// #################################################################
// ################  User - registration   #########################
// #################################################################

/**
 * Reset the image upload form
 */
function resetImage(imageIdElement) {
  imageIdElement.value = '';
  $('imageDisplay').src = '';
  $('imageResetButton').hide();
  $('imageDisplay').hide();
  $('uploadButton').show();
  $('infoButton').show();
}

/**
 * DESCRIPTION: open the AGBs
 *
 * @param url
 * @param string <opt>, desired AGB-template
 * @return -
 */
function show_user_AGB(url,opt) {
  var flags = '';
  window.open(url + "/" + opt, '_blank', flags);
}

/**
 * DESCRIPTION: shows the alternative username, if the username is already given
 *
 * @param request
 * @param _names
 * @param _caller
 * @return -
 */
function showAlternatives(request, _names, _caller) {

  if(_names) {
  var newSelect = $('layerUsernameUsed').innerHTML;
  var SelectLines = "";
  var prefix = newSelect.substr(0, newSelect.indexOf("<!--START") -1);
  if(prefix.length > 0) {                                                     // Determine if formatting was used
    var suffix = newSelect.substr(newSelect.indexOf("END-->") + 6);

    // Extract Formatting String
    var format_string = newSelect.match(/<!--{(.*)}-->/i, newSelect)[1];


    for(var i=0; i < _names.length; i++) {                                     // Create line entry for each username suggestion
    SelectLines += format_string.replace(/%name%/gi,_names[i]).replace(/%count%/gi, i);
    }

    newSelect = prefix + "<!--START--><!--{" + format_string +"}-->" + SelectLines + "<!--END-->"+ suffix;

    $('layerUsernameUsed').innerHTML = newSelect;

  }
  if (_caller=='fullReg') {
    _anchor = 'fusernameLink';
  }
  overlay(_anchor, 'layerUsernameUsed', 'bottom', 'xlinkUsername', 'xlinkUsername', 'buttonIsLeft');
  return false;
  }
  else {
  overlaycloseOnChange('usernameLink', 'layerUsernameUsed', ' ', 'xlinkUsername', 'layerUsernameUsed', 'bottom', 'xlinkUsername', 'xlinkUsername', 'buttonIsLeft');
  }
}


// #################################################################
// ################   Layer - funktions   ##########################
// #################################################################

function overlaycloseOnChange(curobj, subobj, txt, newClassName, newLayerName, newAlignment, classNameOff, classNameOn, buttonpos) {
  var theLayer = document.getElementById(subobj);
  theLayer.hide();
}

function overlay(objToGet, subobjstr, opt_position, classNameOff, classNameOn, buttonPos) {
  if (document.getElementById){

    var subobj=document.getElementById(subobjstr);
    var curobj=document.getElementById(objToGet);

    // which callbacks are possible -- append here addidition callbacks
    var possibleCallBacks = ['focusUsernameElement'];

    /** check, if there is flash to blend out for the big quickreg layer */
    if (navigator.userAgent.indexOf('Mac') >- 1 && objToGet == 'registerLink') {
      flas = $$('.teaserbox object');
      visibility = 'hidden';
      if (subobj.style.display != 'none') {
      visibility = 'visible';
      }
      if (flas.length > 0) {
      for (f=0; f<flas.length; f++) {
        flas[f].style.visibility = visibility;
      }
      }
      //flas.style.display = 'none';
    }

    if (subobj.style.display!="none") {
        subobj.hide();
        curobj.className=classNameOff;
    } else {
        // normally we have six arguments for this method, check if we have seven for special features
        // and if so, check if it's ok.
        if(overlay.arguments.length > 6 && possibleCallBacks.indexOf(overlay.arguments[6]) > -1){
          eval('var myOptions = {duration:0.3, from:0, to:1.0, afterFinish: '+overlay.arguments[6]+' };');
        }else{
          var myOptions = {duration:0.3, from:0, to:1.0};
        }
        subobj.show();
        curobj.className=classNameOn;
    }

    var xpos;
    if (buttonPos == "buttonIsLeft") { //wenn layer rechts vom button öffnet
        // for the layers in userAsset profile: in IE move layer 1px to the left, ph 11.3.07
        var layerXOffset = opt_position.indexOf("arrow") != -1 && navigator.appVersion.match(/\bMSIE\b/) ? -1 : 0;
        xpos=getposOffset(curobj, "left")+((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0) + layerXOffset;
    }
    else if (buttonPos == "buttonIsRight") { //wenn layer links vom button öffnet
        xpos=(getposOffset(curobj, "left")-($(subobj).getWidth()-$(curobj).getWidth()))-((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0);
    }
    else if (buttonPos == "buttonIsRight2") { //wenn layer rechts vom button öffnet, aber icon rechts vom link steht
        xpos=(getposOffset(curobj, "left")-(-$(curobj).getWidth()+32))-((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0);
    }
    else if (buttonPos == "buttonIsRight3") { //wenn layer rechts vom button öffnet, aber icon rechts vom link steht
        xpos=(getposOffset(curobj, "left")-(-$(curobj).getWidth()+39))-((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0);
    }
    // for the layers in userAsset profile: set layer 15px from top (the height of the arrow itself...), ph 11.3.07
    var arrowYOffset = opt_position.indexOf("arrow") != -1 ? 15 : 0;
    var ypos=getposOffset(curobj, "top")+((typeof opt_position!="undefined" && opt_position.indexOf("bottom")!=-1)? curobj.offsetHeight : 0) + arrowYOffset;
    subobj.style.left=xpos+"px";
    subobj.style.top=ypos+"px";
  }
  else
    return true;
}

/**
 * DESCRIPTION: show or hide the LoginLayer;
 *
 * @param string id = id of the LoginLayers;
 * @return -
 */
function toggleLoginHi(id) {
  if (($(id)).hasClassName('hi')) {
    $(id).removeClassName('hi');
    $(id+'Layer').hide();
  }
  else {
  ($(id)).toggleClassName('hi');
  $(id+'Layer').show();
  }
}

/**
 * DESCRIPTION: shows oginLayer;
 *
 * @param string id = id of the LoginLayers;
 * @return -
 */
function showLoginLayer(id) {
  $(id+'Layer').show();
}

/**
 * DESCRIPTION: opens or close the InfoLayer
 *
 * @param string anchor = id of the a-tag (info-iamge) to position the infoLayer
 * @param string infoContent = id of the InfoLayer;
 * @param int myWidth = width of the InfoLayer(default = 220px);
 * @param string pos = "left" or "right", the infoLayer can shown right beside of theinfo-image or left beside  (default = 'left');
 * @return -
 */

var observing = new Array();
function toggleInfoLayer(anchor, infoContent, myWidth, pos) {
  var myOffsetLeft=0;
  if (!myWidth) { myWidth=200;}
  if (!pos) { pos='left';}
  if ($(infoContent+'Gap')) {
  $(infoContent+'Gap').toggle();
  toogleIframe((infoContent+'Gap'));
  }
  else {
  var infoDiv = document.createElement('div');
  infoDiv.id = infoContent+'Gap';
  document.body.appendChild(infoDiv);
  ($(infoContent+'Gap')).addClassName('info');
  if (pos == 'left') {
    (infoDiv).addClassName('le');
  }
  else {
    (infoDiv).addClassName('re');
    myOffsetLeft = 14 - myWidth;
  }
  infoDiv.setStyle({width: myWidth+'px'});

  var infoLayer =	'<div class="bt"></div>' +
        '<div class="gap">' +
        '<div class="cont" id="cont">' +
          $(infoContent).innerHTML +
        '</div>' +
        '</div>';

  infoDiv.innerHTML = infoLayer;

  Element.clonePosition(infoDiv,anchor, {
    setLeft: true,
    setTop: true,
    setWidth: false,
    setHeight: false,
    offsetLeft: myOffsetLeft,
    offsetTop: 16
  });

  toogleIframe((infoDiv.id));
  $(infoDiv).show();
  }
  if (observing.indexOf(infoContent)) {
  observing[observing.size()] = infoContent;
  document.observe('mousedown', function(event) {if ($(infoContent+'Gap').visible()) {toggleInfoLayer(anchor, infoContent, myWidth, pos)}});
  }
}

/**
 * DESCRIPTION: create for the  IE6 an transparent iFrame behind an opening layer to hack the selctbox problem in IE 6
 * The iFrame clons the position and size of the layer
 *
 * @param string anchor = id of the elemente, where and in width the iframe renders
 * @return -
 */
function toogleIframe(anchor) {
  if ((Prototype.Browser.IE) && (navigator.userAgent.split(';')[1].split('MSIE ')[1] < 7)) {
  if ($(anchor+'If')) {
    $(anchor+'If').remove();
  }
  else {
    var myIFrame = document.createElement('iframe');
    myIFrame.id = anchor +'If';
    document.body.appendChild(myIFrame);
    ($(myIFrame)).addClassName('infoIframe');
    Position.clone($(anchor), $(myIFrame), {
      setLeft: true,
      setTop: true,
      setWidth: true,
      setHeight: true,
      offsetLeft: true,
      offsetTop: true
    });
    $(myIFrame).setStyle({
      height: $(myIFrame).getHeight()+2+'px',
      width: $(myIFrame).getWidth()+2+'px',
      left: $(myIFrame).cumulativeOffset()[0]-1+'px',
      top: $(myIFrame).cumulativeOffset()[1]-1+'px'
    });
    }
  }
}

/**
 * DESCRIPTION: opens the Layer "alertMsg" on the semitransparent overlay div
 *
 * @param int myWidth = Width of the Layer (default = 220px);
 * @param msg = the message
 * @return -
 */
function showMsg(myWidth, msg) {
  if (!myWidth) { myWidth=220;}

  $('contMsg').innerHTML = msg;

  if (document.viewport.getHeight() < $('alertMsg').getHeight()) {
  var newPos = document.viewport.getScrollOffsets()[1]+20+'px'
  } else {
  var newPos = ((document.viewport.getHeight()-$('alertMsg').getHeight())/2)+document.viewport.getScrollOffsets()[1]+'px';
  }

  $('alertMsg').setStyle({
  left: ((796-myWidth)/2)+'px',
  width: myWidth+'px',
  zIndex: 1000,
  top: newPos
  });
  $('alertMsg').show();
  openOverlay();
}

/**
 * DESCRIPTION: opens the Layer "alertDiv" on the semitransparent overlay div
 *
 * @param int myWidth = Width of the Layer (default = 220px);
 * @param layerId = fills the layer alertDiv with the innerHTML of layerId (optional)
 * @return -
 */
function showLayer(myWidth, layerId) {
  if (!myWidth) { myWidth=220;}

  if (layerId) {
  $('cont').innerHTML = $(layerId).innerHTML;
  }

  if (document.viewport.getHeight() < $('alertDiv').getHeight()) {
  var newPos = document.viewport.getScrollOffsets()[1]+20+'px'
  } else {
  var newPos = ((document.viewport.getHeight()-$('alertDiv').getHeight())/2)+document.viewport.getScrollOffsets()[1]+'px';
  }

  $('alertDiv').setStyle({
  left: ((796-myWidth)/2)+'px',
  width: myWidth+'px',
  zIndex: 1000,
  top: newPos
  });
  $('alertDiv').show();
  openOverlay();
}

/**
 * DESCRIPTION: open the Overlay Div (semtransparent)
 *
  * @return -
 */
function openOverlay() {
  if ($('overlay')) {
  $('overlay').show();
  toogleIframe('overlay');
  } else {
  var arrayPageSize = getPageSize();
  var overlay = document.createElement('div');
  overlay.id = 'overlay';
  document.body.appendChild(overlay);
  ($('overlay')).addClassName('overlay');
  ($('overlay')).style.height = arrayPageSize[1] + "px";
  ($('overlay')).setOpacity(0.5);
  $('overlay').show();
  // create a-tag to Close the Overlay
  var aClose = document.createElement('a');
  aClose.id = 'overlayClose';
  $('overlay').appendChild(aClose);
  ($('overlayClose')).addClassName('overlayClose');
  ($('overlayClose')).style.height = arrayPageSize[1] + "px";
  ($('overlayClose')).href="javascript:closeOverlay();"
  toogleIframe('overlay');
  }
}

/**
 * DESCRIPTION: close the Overlay Div
 *
 * @return -
 */
function closeOverlay() {
  if($('overlay')) {
  $('overlay').hide();
  toogleIframe('overlay');
  }
  if ($('alertDiv')) {
  $('alertDiv').hide();
  }
  if ($('alertMsg')) {
  $('alertMsg').hide();
  }
}

/**
 * switches to the next gallery
 *
 * @return -
 */
function switchToNextGallery() {
  window.location.href = $("gallerySelect").value;
}


//############################ fancyZoom ##########################
Object.extend(String.prototype, {
  // if a string doesn't end with str it appends it
  ensureEndsWith: function(str) {
    return this.endsWith(str) ? this : this + str;
  },

  // makes sure that string ends with px (for setting widths and heights)
  px: function() {
    return this.ensureEndsWith('px');
  }
});

Object.extend(Number.prototype, {
  // makes sure that number ends with px (for setting widths and heights)
  px: function() {
    return this.toString().px();
  }
});

var Window = {
  // returns correct dimensions for window, had issues with prototype's sometimes. this was ganked from apple.
  size: function() {
    var width  = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
    var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
    var x      = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
    var y      = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
    return {'width':width, 'height':height, 'x':x, 'y':y}
  }
}


var zooming = false;
var setup = false;
var weight;
var height;
var newTop;
var newLeft;
var moveX;
var moveY;

var FancyZoomBox = Class.create();
FancyZoomBox.prototype = {

  initialize: function(id, src, width, height) {
    this.id = id;
    this.src = src;
    this.width = width;
    this.height = height;

    if (setup) return;
    setup = true;

    var ie = navigator.userAgent.match(/MSIE\s(\d)+/);
    if (ie) {
      var version = parseInt(ie[1]);
      Prototype.Browser['IE' + version.toString()] = true;
      Prototype.Browser.ltIE7 = (version < 7) ? true : false;
    }

    var html = '<div id="zoom" style="z-index:1000;display:none;background-color:white;border:1px solid black;"> \
                  <div style="width:100%; height:100%;"> \
                    <a id="zoom_close" href="#" title="Close" style="cursor: pointer"> \
                      <div href="" onclick="hideFancyZoom();return false;" style="display:block;float:right;border:none; padding:3px 15px 0px 0px;">Schlie&szlig;en <img src="/img/icons/x.gif" alt="Schlie&szlig;en" /></div> \
                    </a> \
                    <div style="background-color:white;padding:20px 15px 20px 15px;"> \
                      <div id="zoom_content"></div> \
                    </div> \
                  </div> \
                </div>';

    var body  = $$('body').first();
    body.insert(html);

    // hide zoom if click fired is not inside zoom
    $$('html').first().observe('click', function(e) {
      //var click_in_zoom = e.findElement('#zoom'),
      zoom_display  = $('zoom').getStyle('display');
      if (zoom_display == 'block') {
        hideFancyZoom();
      }
    });

  },

  show: function() {
    if (zooming) return;
    zooming   = true;
    if ($("zoom_content")) {
      $("zoom_content").innerHTML = "";
    }

    // f�r jedes grosse Bild einen Container erstellen:
    var newdiv;
    if (!$('div_'+this.id)) {
      newdiv = document.createElement('div');
      newdiv.setAttribute('id','div_'+this.id);
      newdiv.style.display = "none";
      newdiv.innerHTML = '<img style="display:block;" src="'+this.src+'" width="'+this.width+'" />';
      document.body.appendChild(newdiv);
    } else {
      newdiv = $('div_'+this.id);
    }

    width              = parseInt(this.width) + 30;
    height             = parseInt(this.height) + 40;
    var d              = Window.size();
    var yOffset        = document.viewport.getScrollOffsets()[1];
    // ensure that newTop is at least 0 so it doesn't hide close button
    newTop             = Math.max((d.height/2) - (height/2) + yOffset, 0);
    newLeft            = (d.width/2) - (width/2);

    var curTop    = d.height/2;
    var curLeft   = d.width/2;
    moveX     = -(curLeft - newLeft);
    moveY     = -(curTop - newTop);

    $("zoom").setStyle({
      position	: 'absolute',
      top		: curTop.px(),
      left		: curLeft.px(),
      width     : "0".px(),
      height    : "0".px()
    });


    $("zoom").show();
    new Effect.Parallel([
      new Effect.Move($("zoom"), {x: moveX, y: moveY, sync: true}),
      new Effect.Morph($("zoom"), {
        style: {
          width: width.px(),
          height: height.px()
        },
        sync: true,
        afterFinish: function(effect) {
          $('zoom_content').innerHTML = newdiv.innerHTML;
          zooming = false;
          $('zoom_close').show();
        },
        beforeStart: function() {
          $('zoom_close').hide();
        }
      })
    ], { duration: 0.5 });

    // shows the big grey layer over all..
    openOverlay();
  }
}

function hideFancyZoom() {
    if (zooming) return;
    zooming = true;

    new Effect.Parallel([
      new Effect.Move($('zoom'), {x: moveX*-1, y: moveY*-1, sync: true}),
      new Effect.Morph($('zoom'), {
        style: {
          width: '1'.px(),
          height: '1'.px()
        },
        sync					: true,
        beforeStart: function(effect) {
          $('zoom_content').innerHTML = '';
          $('zoom_close').hide();
        },
        afterFinish: function(effect) {
          zooming = false;
        }
      })
      //,new Effect.Fade($('zoom'), {sync:true})
    ], { duration: 0.5 });

    $("zoom").hide();

    // hides the big grey layer over all..
    closeOverlay();
}

function fancyZoom(id, src, width, height) {
  fzb = new FancyZoomBox(id, src, width, height);
  fzb.show();
}

