/*!
    Slimbox v1.64 - The ultimate lightweight Lightbox clone
    (c) 2007-2008 Christophe Beyls <http://www.digitalia.be>
    MIT-style license.
 */

var Slimbox;

(function() {
  // Global variables, accessible to Slimbox only
  var state = 0, options, images, activeImage, prevImage, nextImage, top, fx, preload, preloadPrev = new Image(), preloadNext = new Image(),
  // State values: 0 (closed or closing), 1 (open and ready), 2+ (open and busy with animation)
 // DOM elements
  overlay, center, image, imageCont, prevLink, nextLink, bottom, caption, number, advert, advertFrame, presFrame, title, kategorie, 
  iframe_zp_slimbox, imageheight, diaAdtagBottom;
// curSitestat, curIvw,

  /*
     Initialization
   */

  // modified by maik.finsterbusch@arithnea.de
  adInfo = {
    imageAsBackground:false,
    link:'',
    image:'',
    trackclickURL:'',
    trackclickType:'',
    softclick:'',
    pixel_internal:'',
    pixel_external:''
  };
  
  defaultImage = {
    width: 500,
    height: 400
  }
  
  adType = 'none';
  sbType = 'none';
  adAsBackground = false;
  diashowID = null;
  kategorie = 'unknownCategory';

  /*
        API
   */

  Slimbox = {
    
    open: function(_images, startImage, _options) {
      adType = 'none';

      options = $extend({
        loop: true,                // Allows to navigate between first and last images
        overlayOpacity: 0.7,            // 1 is opaque, 0 is completely transparent (change the color in the CSS file)
        resizeDuration: 400,            // Duration of each of the box resize animations (in milliseconds)
        resizeTransition: false,        // Default transition in mootools
        startWidth: 520,
        initialWidth: 520,              // Initial width of the box (in pixels)
        initialHeight: 450,             // Initial height of the box (in pixels)
        animateCaption: false,
        showCounter: true,              // If true, a counter will only be shown if there is more than 1 image to display
        counterText: "Bild {x} von {y}",// Translate or change as you wish
        advertise: true
      }, _options || {});

      if (options.advertise) {
        options.initialWidth = 840;
      }
      // Einlesen der Kategorie bezogenen Diashow

      if(true) {
        if(_images[startImage][2] >= 400) {
            $(document.body).adopt(
              $$([
                overlay = new Element("div", {id: 'lbOverlay'}).addEvent('click', close),
                center = new Element('div', {id: 'diaOuterBody', 'class': 'diaOuterBody_sport1'}).adopt(
                  title = new Element('div', {id: 'diaHeadline', 'class': 'diaHeadline font_6'}),
                  image = new Element('div', {id: 'diaImage', 'class': 'diaImage'}),
                  bottom = new Element('div', {id: 'diaBottom', 'class': 'diaBottom'}).adopt(
                    caption =   new Element('div', {id: 'diaText', 'class': 'diaText font_52'}),
                                new Element('div', {id: 'diaSizer', 'class': 'diaSizer'}).adopt(
                                    new Element('div', {id: "diaCloseButton", 'class': 'diaCloseButton'}).addEvent("click", close),
                                    number = new Element('div', {id: 'diaNumber', 'class': 'diaNumber font_35'})
                                ),
                                new Element('div', {id: 'diaAdtagBottom', 'class': 'diaAdtagBottom'})
                    )
                ), 
                zp = new Element("iframe", {id: 'iframe_zp_slimbox', 'class': 'iframe_zp_slimbox', 'frameborder': 'none'})
              ])
            );
        }
        else {
            $(document.body).adopt(
              $$([
                overlay = new Element("div", {id: 'lbOverlay'}).addEvent('click', close),
                center = new Element('div', {id: 'diaOuterBody', 'class': 'diaOuterBody'}).adopt(
                  title = new Element('div', {id: 'diaHeadline', 'class': 'diaHeadline font_6'}),
                  image = new Element('div', {id: 'diaImage', 'class': 'diaImage'}),
                  bottom = new Element('div', {id: 'diaBottom', 'class': 'diaBottom'}).adopt(
                    caption =   new Element('div', {id: 'diaText', 'class': 'diaText font_52'}),
                                new Element('div', {id: 'diaSizer', 'class': 'diaSizer'}).adopt(
                                  new Element('div', {id: "diaCloseButton", 'class': 'diaCloseButton'}).addEvent("click", close),
                                  number = new Element('div', {id: 'diaNumber', 'class': 'diaNumber font_35'})
                                ),
                                new Element('div', {id: 'diaAdtagBottom', 'class': 'diaAdtagBottom'})    
                 )
                ), 
                zp = new Element("iframe", {id: 'iframe_zp_slimbox', 'class': 'iframe_zp_slimbox', 'frameborder': 'none'})
              ])
            );
        }
        fx = {
          overlay: new Fx.Tween(overlay, {property: "opacity", duration: 500}).set(0),
          bottom: new Fx.Tween(bottom, {property: "margin-top", duration: 400})
        };
      }

      // The function is called for a single image, with URL and Title as first two arguments
      if (typeof _images == "string") {
        _images = [[_images,startImage]];
        startImage = 0;
      }
         
      // maik.finsterbusch@arithnea.de
      // trigger out if we are a diashow or a zai
      // and fill options.advertisement
      if (options.zoomedArticleImage){
        sbType = 'zoomedArticleImage';
      } else {
        sbType = 'diashow';
        prevLink = new Element('a', {id: "diaPreviousButton", 'class': 'diaPreviousButton', 'href': '#'}).injectInside(image).addEvent("click", previous);
        nextLink = new Element('a', {id: "diaNextButton", 'class': 'diaNextButton', 'href': '#'}).injectInside(image).addEvent("click", next);
      }
 
      if(typeof(options.presVO) != 'undefined') {
        if (typeof(options.presVO.presenting_diashow_activated) != 'undefined') {
          if (options.presVO.presenting_diashow_activated == true) {
            adType = 'presVO';
          }
        }
        if(typeof(options.presVO.presenting_diashow_flash_activated) != 'undefined') {
          if(options.presVO.presenting_diashow_flash_activated == true) {
            adType = 'presFlash';
          }
        }
      }
        
      switch(adType){
        case 'presVO':
          adInfo = {
            imageAsBackground:options.presVO.presenting_diashow_imageAsBackground,
            link:options.presVO.presenting_diashow_link,
            image:options.presVO.presenting_diashow_image,
            imageAbsolute:options.presVO.presenting_diashow_imageAbsolute,
            imageWidth:options.presVO.presenting_diashow_imageWidth,
            imageHeight:options.presVO.presenting_diashow_imageHeight,
            trackclickURL:options.presVO.presenting_diashow_trackclickURL,
            trackclickType:options.presVO.presenting_diashow_trackclickType,
            softclick:options.presVO.presenting_diashow_softclick,
            pixel_internal:options.presVO.presenting_diashow_pixel_internal,
            pixel_external:options.presVO.presenting_diashow_pixel_external
          }
          options.advertisement = {link:adInfo.link,image:adInfo.image,form:'picture'};
          // Add presenting element label to sitestat custom label, if present
        break;
        case 'presFlash':
          adInfo = {
            swfSrc:options.presVO.presenting_diashow_flash_src,
            link:options.presVO.presenting_diashow_flash_link,
            swfHeight:options.presVO.presenting_diashow_flashHeight,
            swfWidth:options.presVO.presenting_diashow_flashWidth,
            swfVersion:options.presVO.presenting_diashow_flash_version,
            softclick:options.presVO.presenting_diashow_flashSoftclick,
            backgroundColor:options.presVO.presenting_diashow_flashBackgroundColor,
            textColor:options.presVO.presenting_diashow_flashTextColor,
            pixel_internal:options.presVO.presenting_diashow_flashPixelInternal,
            pixel_external:options.presVO.presenting_diashow_flashPixelExternal
          }
          options.advertisement = {form:'flash'};
        break;
        default://default is no presenting and no ad
          break;
      }

      if(typeof(adInfo.imageAsBackground) == 'undefined') {
        adInfo.imageAsBackground = false;
      }
      adAsBackground = adInfo.imageAsBackground;
      // /mfinsterbusch

      // Berechnung der Box Position
      top = window.getScrollTop() + (window.getHeight() / 15);
      left = (window.getWidth() / 2) - (options.initialWidth / 2);
      
      if (options.advertisement) {

        if (options.advertisement.form == 'picture') {
          // Presenting
          center.setStyles({backgroundImage: 'url('+ adInfo.imageAbsolute +')', backgroundRepeat: 'no-repeat',
                            width: adInfo.imageWidth + 'px', minHeight: adInfo.imageHeight + 'px'});
          presFrame = new Element('div', {id: 'diaPresClick', 'class': 'diaPresClick'}).injectInside(center).addEvent("click", presentingClicked);
          presFrame.setStyles({ left: (defaultImage.width + 10) + 'px', width: (adInfo.imageWidth - (defaultImage.width + 10)) + 'px', height: adInfo.imageHeight + 'px'});
        } 
        else if (options.advertisement.form == 'flash') {
          newWidth = options.startWidth + parseInt(adInfo.swfWidth);
          newHeight = (options.initialHeight > parseInt(adInfo.swfHeight))? options.initialHeight : parseInt(adInfo.swfHeight);
          backgrColor = (adInfo.backgroundColor != '')? adInfo.backgroundColor : '#FFFFFF';
          
          center.setStyles({width:newWidth+'px', height:newHeight+'px', backgroundColor:backgrColor});
 
          if (adInfo.textColor != '') {
            title.setStyles({color:adInfo.textColor});
          }
          
          flashDiv = new Element('div', {id:'dia_pres_flash'}).injectInside(center);
          flashvars = {clicktag:adInfo.link};
          
          if (adInfo.softclick != '') {
            flashvars.softLabel = adInfo.softclick;
          }
          
          params = {menu:false};
          attributes = {};
          Sport1.writeFlash(adInfo.swfSrc, 'dia_pres_flash', adInfo.swfWidth, adInfo.swfHeight, adInfo.swfVersion + '.0.0', flashvars, params, attributes);
          flashvars = {};params = {};attributes = {};
          
          flashElement = document.getElementById('dia_pres_flash');	
          flashElement.style.position = 'absolute';
          flashElement.style.left = options.startWidth + 'px';
          flashElement.style.top = '0px';
        }
      } 
      else {

        if (options.advertise) {
          // Rectangle
          center.setStyle('width', options.initialWidth + 'px');
          advert = new Element('div', {id: 'diaAdvert', 'class': 'diaAdvert'}).injectInside(center).adopt(
            advertFrame = new Element('iframe', {id: 'diaRec', width: '315', height: '256', scrolling: 'no', frameborder: '0'})
          );
        }

      }
              
      images = _images;
      options.loop = options.loop && (images.length > 1);
      position();
      setup(true);
      center.setStyles({top: top, left: left, display: ""});
      fx.overlay.start(options.overlayOpacity);
      state = 1;

      if (options.title != undefined) {
        title.innerHTML = options.title;
      }
        
      if (options.diashowID != undefined) {
        diashowID = options.diashowID;
      }

      if (options.kategorie != undefined) {
        kategorie = options.kategorie;
      }
      // maik.finsterbusch@arithnea.de
      return changeImage(startImage);
    }
  };
// ####################

    

  Element.implement({
    slimbox: function(_options, linkMapper) {
      // The processing of a single element is similar to the processing of a collection with a single element
      $$(this).slimbox(_options, linkMapper);
      return this;
    }
  });

  Elements.implement({
    /*
      options:    Optional options object, see Slimbox.open()
      linkMapper: Optional function taking a link DOM element and an index as arguments and returning an array containing 2 elements:
              the image URL and the image caption (may contain HTML)
      linksFilter:    Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
              the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
              This function must always return true when the DOM element argument is "this".
     */
    slimbox: function(_options, linkMapper, linksFilter) {
      linkMapper = linkMapper || function(el) {
        return [el.href, el.title];
      };

      linksFilter = linksFilter || function() {
        return true;
      };

      var links = this;

      links.removeEvents("click").addEvent("click", function() {
        // Build the list of images that will be displayed
        var filteredLinks = links.filter(linksFilter, this);
        return Slimbox.open(filteredLinks.map(linkMapper), filteredLinks.indexOf(this), _options);
      });

      return links;
    }
  });


  /*
    Internal functions
   */

  function position() {
    overlay.setStyles({top: window.getScrollTop(), height: window.getHeight()});
  }

  function setup(open) {
    ['object', 'iframe', window.ie ? 'select' : 'embed'].forEach(function(tag) {
      Array.forEach(document.getElementsByTagName(tag), function(el) {
        if (el.getAttribute('id') != 'diaRec' && 
            el.getAttribute('id') != 'dia_pres_flash') {
          if (open) el._slimbox = el.style.visibility;
            el.style.visibility = open ? "hidden" : el._slimbox;
        }
      });
    });

    overlay.style.display = open ? "" : "none";

    var fn = open ? "addEvent" : "removeEvent";
    window[fn]("scroll", position)[fn]("resize", position);
    document[fn]("keydown", keyDown);
  }

  function keyDown(event) {
    switch(event.code) {
      case 27:    // Esc
      case 88:    // 'x'
      case 67:    // 'c'
        close();
        break;
      case 37:    // Left arrow
      case 80:    // 'p'
        previous();
        break;  
      case 39:    // Right arrow
      case 78:    // 'n'
        next();
    }
    // Prevent default keyboard action (like navigating inside the page)
    return false;
  }

  function previous() {
    return changeImage(prevImage);
  }

  function next() {
    return changeImage(nextImage);
  }
    
  function presentingClicked() {
    if (typeof(options.presVO.presenting_diashow_softclick) != 'undefined' && options.presVO.presenting_diashow_softclick != '') {
      Sport1_Tracking.trackClick('', options.presVO.presenting_diashow_softclick);
    }
    window.open(options.advertisement.link);
  }

  function changeImage(imageIndex) {
    if ((state == 1) && (imageIndex >= 0)) {
      activeImage = imageIndex;
      prevImage = ((activeImage || !options.loop) ? activeImage : images.length) - 1;
      nextImage = activeImage + 1;
      if (nextImage == images.length) nextImage = options.loop ? 0 : -1;
      preload = new Image();
      preload.src = images[imageIndex][0];
      image.setStyles({backgroundImage: "url(" + images[activeImage][0] + ")", display: ''});
      // imageheight = images[activeImage][2]; 
      nextEffect();
    }
		
    var trackTitle = 'unknownTitle';
    if (options.title != undefined && options.title != null) {
    	trackTitle = escape(options.title);
    }
    var trackKategorie = 'unknownCategory';
    if (options.kategorie != undefined && options.kategorie != null) {
    	trackKategorie = escape(options.kategorie);
    }
    // GLOBAL['sp1SitestatUrl']+'_'+ is prefixed automaticly by countivw()
    var trackCode	= sbType+'__'+trackTitle+'_'+trackKategorie;
	
    /*
    // if diashow is presented, add a custom label to trackCode and insert couterpixels
    if (adType == 'presVO' || adType == 'presFlash') {//add custom label here #marker
    	trackCode	+=	'';
      // Soll als staendiger Kundezaehlpixel genutzt werden
      if (typeof(adInfo.pixel_internal) != 'undefined') {
    	if (adInfo.pixel_internal != '') {
            Sport1_Tracking.callExtTracker(adInfo.pixel_internal, 'url', 0);
    	}
      }
    
      // Soll beim Aufruf einmal gezaehlt werden
      if (typeof(adInfo.pixel_external) != 'undefined') {
    	if (adInfo.pixel_external != '') {
               Sport1_Tracking.callExtTracker(adInfo.pixel_external, 'url', 0);
    	}
      }
    }
    */

    if (options.advertise) {
      // Rectangle
      center.setStyle('width', '840px');
      advert = new Element('div', {id: 'diaAdvert', 'class': 'diaAdvert'}).injectInside(center).adopt(
        advertFrame = new Element('iframe', {id: 'diaRec', width: '315', height: '256', scrolling: 'no', frameborder: '0'})
      );
    }

	if(document.getElementById('iframe_zp_slimbox')) {
        document.getElementById('iframe_zp_slimbox').src = "/de/includes/nav/netrating/content_iframe.htm";
    }

	if(document.getElementById('diaAdtagBottom')) {
        adTagBottomContent = ''+
            '<iframe allowtransparency="true"'+
            ' src="http://ff.connextra.com/Interwetten/selector/client?client=Interwetten&placement=sport1_ch_468x60"'+
            ' width="468" height="60"'+
            ' scrolling="no" frameborder="0"'+
            ' style="border-width:0"></iframe>'+
            ''; 
        document.getElementById('diaAdtagBottom').innerHTML = adTagBottomContent;
    }

  	return false;
  }

  function nextEffect() {
    caption.set('html', images[activeImage][1] || "");
    number.set('html', (options.showCounter && (images.length > 1)) ? options.counterText.replace(/{x}/, activeImage + 1).replace(/{y}/, images.length) : "");

    if (prevImage >= 0) preloadPrev.src = images[prevImage][0];
    if (nextImage >= 0) preloadNext.src = images[nextImage][0];

    if (options.animateCaption && typeof(options.advertisement) == 'undefined') {
      fx.bottom.set(-bottom.offsetHeight).start(0);
    }
    
    if (typeof(options.advertisement) == 'undefined' && options.advertise) {
        advertFrame.setAttribute('src', '/de/includes/nav/adtags/lightboxad.htm');
    }
    
    if ((image.offsetHeight != preload.height && preload.height != defaultImage.height && preload.height != 0) || 
        (image.offsetWidth != preload.width && preload.width != defaultImage.width && preload.width != 0)) {
      resizeImageBox();
    } else {
      removeImageStyles();
    }
  }

  function resizeImageBox() {
    var calcWidth = 20;
  
    if (options.advertisement) {
      presFrame.setStyles({left: (preload.width + 10) + 'px', width: (adInfo.imageWidth - (preload.width + 10)) + 'px'});
    } else {
      center.setStyles({width: image.offsetWidth + calcWidth});
      image.setStyles({width: image.offsetWidth, height: image.offsetHeight});
      prevLink.setStyles({height: image.offsetHeight});
      nextLink.setStyles({height: image.offsetHeight});
    }
  }
  
  function removeImageStyles() {
    if(image.offsetHeight != defaultImage.height ||
       image.offsetWidth != defaultImage.width
    ) {
      center.setStyles({});
      image.setStyles({});
      prevLink.setStyles({});
      nextLink.setStyles({});
      if (options.advertisement) {
          presFrame.setStyles({left: (preload.width + 10) + 'px', width: (adInfo.imageWidth - (preload.width + 10)) + 'px'});
      }
    }
  }
  
  function close() {
    if (state) {
      state = 0;
      preload.onload = $empty;
      for (var f in fx) fx[f].cancel();
      $$(center).setStyle("display", "none");
      fx.overlay.chain(setup).start(0);
    }
    resetStyles();
    return false;
  }
	
	// resets all styles to make style free for non-presented slimboxes
  function resetStyles(){
    var elems	= new Array();
	elems[0]	= 'lbOverlay';
    elems[1]    = 'diaOuterBody';
    elems[2]    = 'iframe_zp_slimbox';
    
    for (var i=0;i<elems.length ;i++) {
        try {
            var el = document.getElementById(elems[i]);
            el.parentNode.removeChild(el);
        }
        catch(e) {
        }
	}
    return true;
  }
})();

