// Input-Felder: Value ein- und ausblenden
var inputValueHash = new Hash();

function init_input_toggle() {
    if ($$('.toggle')) {
        $$('.toggle').each(function(feld) {
            inputValueHash.set(feld.id, feld.value);
            feld.observe('focus', inputFocus);
            feld.observe('blur', inputBlur);
        });
    }
}
function inputFocus(event) {
    var inputEl = event.element();
    if (inputEl.value == inputValueHash.get(inputEl.id)) {
        inputEl.value = '';
        inputEl.style.color = '#222';
    }
}
function inputBlur(event) {
    var inputEl = event.element();
    if (inputEl.value == '') {
        inputEl.value = inputValueHash.get(inputEl.id);
        inputEl.style.color = '#f00000';
    }
}

// target="_blank" per Javascript anfuegen
function externalLinks() {
  if (!document.getElementsByTagName) return;
      var anchors = document.getElementsByTagName("a");
      for (var i=0; i<anchors.length; i++) {
          var anchor = anchors[i];
          if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
              anchor.target = "_blank";
      }
}


/*  ==========================================================================================================  */
/*  ibSlider v 1.1.0
/*  ==========================================================================================================  */
/*  ChangeLog (07.04.2010)

    - No more ugly "var ctx = this" notations.
    - Fixed a major bug, where multiple autosliders didn't work

    @TODO: try removing more vars by replacing them with this.{name} ...

/*  ==========================================================================================================  */
/*  The Slider
/*  ==========================================================================================================  */

    var SlidingBox = Class.create({

        // Don't like the CSS classnames? Change'em here...
        classNames : {
            slider          : 'slider',         //
            slideLeft       : 'slide-left',     //
            slideRight      : 'slide-right',    //
            slideMask       : 'slide-mask',     //
            slideContent    : 'slide-content'   //
        },

        setOptions: function(opt) {
            this.options = {
                infinite: false,
                increments: null,
                duration: 1,
                autoslide: false,
                delay: 6
            };
            Object.extend(this.options, opt || {});
        },

        initialize: function(sbox, opt) {
            // Set the options
            this.setOptions(opt);
            if (this.options.autoslide === true) this.options.infinite = true;

            // set up some vars
            this.slider         = sbox;
            this.container      = this.slider.down('.'+this.classNames.slideContent);
            this.mask           = this.slider.down('.'+this.classNames.slideMask);
            this.item           = this.slider.down('li');
            this.itemCount      = this.slider.select('li').size();
            this.itemWidth      = this.getItemWidth();
            this.increments     = this.getIncrements();
            this.scroll_offset  = this.itemWidth * this.increments;
            this.triggerLeft    = this.slider.down('.'+this.classNames.slideLeft);
            this.triggerRight   = this.slider.down('.'+this.classNames.slideRight);

            this.triggerLeft.style.visibility = 'visible';
            this.triggerRight.style.visibility = 'visible';
            // set up the slide-container width
            this.setSlidingContainer();
            // initially disable triggers, slideLeft always...
            $$('.'+this.classNames.slideLeft).invoke('addClassName', 'inactive');
            // ... and slideRight, if there are too few items in the slider
            if (this.itemCount <= this.increments) {
                $$('.'+this.classNames.slideRight).invoke('addClassName', 'inactive');
            }
            if (this.options.autoslide === true) {
                this.horizontal_slider();
            }
        },

        getItemWidth: function() {
            var itemWidth = (this.item.getWidth()) + (parseInt(this.item.getStyle('margin-right'))) + (parseInt(this.item.getStyle('margin-left')));
            return itemWidth;
        },

        // how many items to move at a time
        getIncrements: function() {
            // Either it's declared by options
            if (this.options.increments !== null) {
                this.increments = this.options.increments;
            // or increment is set to the number of visible items
            } else {
                var maskWidth = this.mask.getWidth();
                this.increments = Math.round(maskWidth / this.itemWidth);
            }
            return this.increments;
        },

        setSlidingContainer: function() {
            var containerWidth  = (this.itemWidth * this.itemCount);
            this.container.setStyle({
                left: 0,
                width: containerWidth + 'px'
            });
            // now, bind event handler to the box
            this.slider.observe('click', this.slideBoxEvents.bindAsEventListener(this));
        },

        // figure out which element was clicked and say what happens next
        slideBoxEvents: function(event) {
            var trigger = event.element();
            if ((trigger.match('.'+this.classNames.slideLeft) || trigger.match('.'+this.classNames.slideRight))) {
                Event.stop(event); // stop default behaviour of trigger element
                if (!trigger.hasClassName('inactive')) {
                    this.horizontal_slider(trigger);
                }
            } else return;
        },

        // Same as slideRight, but separated to run in it's own scope (effect queue)
        autoSlide: function(trigger, scroll_offset, duration, lastMargin, max_position, maskSize, startOver) {
            if (this.options.autoslide) {
                window.clearTimeout(this.timeoutId);
            }

            new Effect.Move(this.container, {
                x: -(scroll_offset),
                y: 0,
                mode: 'relative',
                duration: duration,
                queue: {position: 'end', scope: 'autoslide', limit: 0}, // Do never limit this, it would destroy multiple auto-sliders with same delay
                afterFinish: function() {
                    max_position = max_position - scroll_offset - lastMargin;
                    // toggle triggers inactive-state
                    if (max_position <= maskSize) {
                        trigger.addClassName('endpoint');
                    }
                    this.triggerLeft.removeClassName('inactive');
                    this.horizontal_slider();
                }.bind(this)
            });
        },

        slideRight: function(trigger, scroll_offset, duration, lastMargin, max_position, maskSize, startOver) {
            if (this.options.autoslide) {
                window.clearTimeout(this.timeoutId);
            }
            new Effect.Move(this.container, {
                x: -(scroll_offset),
                y: 0,
                mode: 'relative',
                duration: duration,
                queue: {position: 'end', scope: 'anims', limit: 1},
                afterFinish: function() {
                    max_position = max_position - scroll_offset - lastMargin;
                    // toggle triggers inactive-state
                    if (max_position <= maskSize) {
                        if (startOver === true) {
                            trigger.addClassName('endpoint')
                        } else {
                            trigger.addClassName('inactive');
                        }
                    }
                    this.triggerLeft.removeClassName('inactive');
                    if (this.options.autoslide) {
                        this.horizontal_slider();
                    }
                }.bind(this)
            });
        },

        slideLeft: function(trigger, scroll_offset, duration) {
            var scroll_target = this.container;

            if (this.options.autoslide) {
                window.clearTimeout(this.timeoutId);
            }
            new Effect.Move(scroll_target, {
                x: scroll_offset,
                y: 0,
                mode: 'relative',
                duration: duration,
                queue: {position: 'end', scope: 'anims', limit: 1},
                afterFinish: function() {
                    actual_position = parseInt(scroll_target.getStyle('left'));
                    // toggle triggers inactive-state
                    if (actual_position >= 0) {
                        trigger.addClassName('inactive');
                    }
                    this.triggerRight.removeClassName('inactive').removeClassName('endpoint');
                    if (this.options.autoslide) {
                        this.horizontal_slider();
                    }
                }.bind(this)
            });
        },

        slideBack: function(duration) {
            if (this.options.no_animation) {
                this.container.setStyle({left: 0});
                this.triggerRight.removeClassName('inactive').removeClassName('endpoint');
                this.triggerLeft.addClassName('inactive');
                if (this.options.autoslide === true) {
                    this.horizontal_slider();
                }
            } else {
                new Effect.Move(this.container, {
                    x: 0,
                    y: 0,
                    mode: 'absolute',
                    duration: duration,
                    queue: {position: 'end', scope: 'anims', limit: 0}, // Do never limit this, it would destroy multiple auto-sliders with same delay
                    afterFinish: function() {
                        this.triggerRight.removeClassName('inactive').removeClassName('endpoint');
                        this.triggerLeft.addClassName('inactive');
                        if (this.options.autoslide === true) {
                            this.horizontal_slider();
                        }
                    }.bind(this)
                });
            }
        },

        horizontal_slider: function(trigger) {
            var maskSize        = this.mask.getWidth();
            var lastMargin      = parseInt(this.item.getStyle('margin-right'));
            var startOver       = this.options.infinite;
            var duration        = this.options.duration;
            var scroll_offset   = this.scroll_offset;
            var actual_position = (Math.abs(parseFloat(this.container.style.left)));
            var max_position    = parseInt(this.container.getStyle('width')) - actual_position;
            var containerWidth  = (this.itemWidth * this.itemCount);

            if (this.options.autoslide === true && trigger === undefined) {
                var delay     = this.options.delay;
                var trigger   = this.triggerRight;

                var sb = this.slideBack.bind(this, duration); // slideBack
                var as = this.autoSlide.bind(this, trigger, scroll_offset, duration, lastMargin, max_position, maskSize, startOver); // autoSlide

                if (max_position <= (maskSize + lastMargin)) {
                    this.timeoutId  = window.setTimeout(function() {sb();}, delay * 1000);
                } else {
                    this.timeoutId  = window.setTimeout(function() {as();}, delay * 1000);
                }
            }
            // Slide right
            else if (trigger.hasClassName(this.classNames.slideRight)) {
                var newOffset = containerWidth - maskSize - actual_position;
                if (scroll_offset > newOffset) {
                    var newInc = Math.round(newOffset / this.itemWidth);
                    scroll_offset = this.itemWidth * newInc;
                }
                // if set to infinite, start over
                if (startOver === true && trigger.hasClassName('endpoint')) {
                    this.slideBack(duration);
                }
                // standard movement
                if (max_position > maskSize) {
                    this.slideRight(trigger, scroll_offset, duration, lastMargin, max_position, maskSize, startOver);
                }
            // Slide left
            } else if (trigger.hasClassName(this.classNames.slideLeft)) {
                if (actual_position < scroll_offset) {
                    this.slideBack(duration);
                } else if (actual_position != '0') {
                    this.slideLeft(trigger, scroll_offset, duration);
                }
            }
        }
    });

/*  ==========================================================================================================  */
/*  Fading Teaser Box
/*  ==========================================================================================================  */

var FadingTeaser = Class.create({

   initialize: function(container, auszeit) {
       this.container   = container;
       this.allSlides   = container.select('a');
       this.allImages   = container.select('img');
       this.navElements = container.select('li');

       this.allSlides.invoke('hide');
       this.allImages.invoke('hide');
       this.allSlides.first().show();
       this.allImages.first().show();
       this.navElements.first().addClassName('active');

       this.navElements.invoke('observe', 'click', this.slide.bind(this))

       this.auszeit     = auszeit;
       s                = this.slide;
       ctx              = this;
       this.timeoutId   = window.setTimeout(function() {s(null, ctx)}, auszeit*1000);
   },

   slide: function(event, context) {
       if (undefined == context) {
           context = this;
       }
       if (event) {
           window.clearTimeout(context.timeoutId);
           var _nextPos = event.element();
           if (_nextPos.hasClassName('active')) {
               return false;
           }
       } else {
           var currentPos = context.container.select('li.active')[0];
           if (currentPos == context.container.select('li').last()) {
               _nextPos = context.navElements.first();
           } else {
               _nextPos = context.navElements[context.navElements.indexOf(currentPos)+1];
           }
       }
       var _nextSlide = context.allSlides[context.navElements.indexOf(_nextPos)];

       context.navElements.invoke('removeClassName', 'active');
       _nextPos.addClassName('active');

       context.allSlides.each(function(item) {
           if (!(item.style.display == 'none')) {
               Effect.Fade(item.firstDescendant(), {duration: 1.4}); // beware of the images inside, they need to be faded too - for IE's sake
               Effect.Fade(item, {duration: 1.4});
           }
       });
       Effect.Appear(_nextSlide, {duration: 1});
       Effect.Appear(_nextSlide.firstDescendant(), {duration: 1});
       context.timeoutId = window.setTimeout(function() {s(null, context)}, context.auszeit*1000);
   }

});

/* bookmark */
function bookmark(URL, Title)
{
    if (window.sidebar)
    {
        // firefox
        window.sidebar.addPanel(Title, URL, "");
    }
    else if(window.opera && window.print)
    {
        // opera
        var elem = document.createElement('a');
        elem.setAttribute('href', URL);
        elem.setAttribute('title', Title);
        elem.setAttribute('rel', 'sidebar');
        elem.click();
    }
    else if(document.all)
    {
        // ie
        window.external.AddFavorite(URL, Title);
    }
}

/*  ==========================================================================================================  */
/*  Ausklappbox
/*  ==========================================================================================================  */
function toggleForms(event) {
    
    var elToShow = this.up().next('.togglebox');
    if (elToShow) {
    	if (!(this.up().next().hasClassName('togglebox'))) {
    		elToShow = false;
    	}
    } else {
    	elToShow = false;
	}
	  
    var elToHide = this.up(1).select('.togglebox');
    elToHide.each(function(hideme) {
       if (hideme.style.display == 'none') {return false};
       new Effect.BlindUp(hideme, {duration: 0.5});
       
       /* uncheck all radiobuttons within a togglebox */
       var variousRadioBtn = hideme.select('input[type=radio]');
       variousRadioBtn.each(function(singleRadioBtn) {
           singleRadioBtn.checked = false;
       })
    });

    if (elToShow != false && elToShow.style.display == 'none') {
       new Effect.BlindDown(elToShow, {duration: 0.5});
    }
    
}


/*  ==========================================================================================================  */
function init() {

    // Input Field Value toggle
    init_input_toggle();

    // External Links
    externalLinks();
    
    // Mainteaser Fades
    if ($('teaser-fader')) {
        var el = $('teaser-fader');
        new FadingTeaser(el, 15);
    }
    
    // Product Slider
    if ($$('.slider').size() >= 1) {
        $$('.slider').each(function(box) {
            if (box.hasClassName('slider-abo')) {
                new SlidingBox(box, {
                    autoslide: true,
                    no_animation: true,
                    delay: 2
                });
            } else {
                new SlidingBox(box);
            }
        });
    }

    // abo form
    if ($$('.togglebox').length >= 1) {
        $$('li > input[type=radio]').each(function(radiobtn) {
            if (radiobtn.checked == false && radiobtn.up().next() && radiobtn.up().next().hasClassName('togglebox')) {
                radiobtn.up().next().hide();


            }
        });
        if (!Prototype.Browser.IE) {
            $$('input[type=radio]').invoke('observe', 'change', toggleForms);
        } else {
            $$('input[type=radio]').invoke('observe', 'click', toggleForms);
        }
    }  

				$('hidden').hide();
				$$('.hider').each(function(box){
					box.observe('click', function(event) {
						$('hidden').show();
						this.hide();
						
					});
				});    

}

// Initialisierung nach Event DOMContentLoaded
document.observe("dom:loaded", init);
