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

function init_input_toggle() {
    var fields = $$('input.toggle'); /* @TODO: Doesnt work in IE */

    fields.each(function(feld) {
        if (feld.value == '') {return false;}
        inputValueHash.set(feld.id, feld.value);
        feld.style.color = '#999';
        feld.observe('focus', inputFocus);
        feld.observe('blur', inputBlur);
    });
}
function inputFocus(event) {
    if (this.value == inputValueHash.get(this.id)) {
        this.value = '';
        this.style.color = '#222';
    }
}
function inputBlur(event) {
    if (this.value == '') {
        this.value = inputValueHash.get(this.id);
        this.style.color = '#999';
    }
}

function toggleForms(event) {

    var elToShow = this.up().next('.togglebox');
    if (!(this.up().next().hasClassName('togglebox'))) {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});
    });

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



/*  ==========================================================================================================  */
/*  ibSlider
/*  ==========================================================================================================  */

var SlidingBox = Class.create({

    _offset: null,
    increments: 2,  // want to change default increments?
    itemCount: '',

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

    getContainer: function(sbox) {
        var container = sbox.down('.'+this.classNames.slideContent);
        return container;
    },

    getItems: function(container) {
        itemCount = container.select('li').size();
        return itemCount;
    },

    initialize: function(sbox) {
        var container   = this.getContainer(sbox);
        increments      = this.getIncrements(sbox);
        var itemCount   = this.getItems(container);

        this.setSlidingContainer(sbox);
        $$('.'+this.classNames.slideLeft).invoke('addClassName', 'inactive');   // hide left scroll links
        // @TODO: if there's no move-x class, this will not work
        if (itemCount <= increments) {
            $$('.'+this.classNames.slideRight).invoke('addClassName', 'inactive');
        }
    },

    setSlidingContainer: function(sbox) {
        // get all vars...
        var container       = sbox.down('.'+this.classNames.slideContent);
        var itemCount       = container.select('li').size();
        this._offset        = this.getScrollOffset(sbox); // get total width of child element
        var containerWidth  = (this._offset / increments) * itemCount;
        // ... and set container width
        container.setStyle({
            left: 0,
            width: containerWidth + 'px'
        });
        // now, bind event handler to the box
        sbox.observe('click', this.slideBoxEvents.bindAsEventListener(this));
    },

    // how many items to move at a time
    getIncrements: function(box) {
        var value = box.classNames().inspect(); // get all the applied classnames
        if (value.indexOf('move-') != -1) {
            inc = parseInt(value.split('-')[1]);
            this.increments = inc;
        }
        return this.increments;
    },

    getScrollOffset: function(box) {
        if (!box.hasClassName(this.classNames.slider)) {
            box = box.up('.'+this.classNames.slider);
        }
        var con         = box.down('.'+this.classNames.slideContent);
        var items       = con.childElements('li'); // get children
        var obj         = items.first();
        this._offset    = parseInt(obj.getWidth()) + parseInt(obj.getStyle('margin-right')) + parseInt(obj.getStyle('margin-left'));
        increments      = this.getIncrements(box);

        return this._offset * increments;
    },

    // figure out which element was clicked and say what happens next
    slideBoxEvents: function(event) {
        trigger = event.element();
        // ... this is a scroll trigger...
        if ((trigger.match('.'+this.classNames.slideLeft) || trigger.match('.'+this.classNames.slideRight)) && !trigger.hasClassName('inactive') ) {
            this.horizontal_slider(trigger);
        // ... or nothing
        } else {
            return false;
        }
    },

    horizontal_slider: function(trigger) {
        var actual_position, max_position, scroll_target;
            scroll_offset = this.getScrollOffset(trigger);
        // Slide right
        if (trigger.hasClassName(this.classNames.slideRight)) {
            scroll_target   = trigger.previous().firstDescendant(); // container element to scroll
            var maskSize    = parseInt(scroll_target.up().getWidth());
            actual_position = (Math.abs(parseFloat(scroll_target.style.left)));
            max_position    = parseInt(scroll_target.getStyle('width')) - actual_position; // stop scrolling at this point
            var lastMargin  = parseInt(scroll_target.firstDescendant().getStyle('margin-right'));
            // scroll inner element and stop at max value
            if (max_position > maskSize) {
                new Effect.Move(scroll_target, {
                    x: -(scroll_offset),
                    y: 0,
                    mode: 'relative',
                    queue: {position: 'end', scope: 'anims', limit: 1}
                });
                max_position = max_position - scroll_offset - lastMargin;
                // toggle triggers inactive-state
                if (max_position <= maskSize) {
                    trigger.addClassName('inactive');
                }
                triggerLeft = trigger.previous(1);
                triggerLeft.removeClassName('inactive');
            }
        // Slide left
        } else if (trigger.hasClassName(this.classNames.slideLeft)) {
            scroll_target = trigger.next().firstDescendant(); // inner element to scroll
            actual_position = (Math.abs(parseFloat(scroll_target.getStyle('left'))));
            // scroll inner element and stop at max value
            if (actual_position != '0') {
                new Effect.Move(scroll_target, {
                    x: scroll_offset,
                    y: 0,
                    mode: 'relative',
                    queue: {position: 'end', scope: 'anims', limit: 1}
                });
                // toggle triggers inactive-state
                actual_position = parseInt(scroll_target.getStyle('left')) + (scroll_offset);
                if (actual_position >= 0) {
                    trigger.addClassName('inactive');
                }
                var triggerRight = trigger.next(1);
                triggerRight.removeClassName('inactive');
            }
        }
    }
});

/*  ==========================================================================================================  */
/*  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);
   }

});

/*  ==========================================================================================================  */
/*  Tooltips for the Slider
/*  ==========================================================================================================  */

function showTip(event) {
    var a = event.element();
    if (a.tagName == 'A' || a.tagName == 'IMG') {
        if (a.tagName == 'IMG') {
            a = a.up('a');
        }
    } else {
        return false;
    }
    var text        = a.getAttribute('title');
    var destination = a.href;
    a.setAttribute('title', '');

    if ($$('.tooltip') < 1) {
        var newTip = new Element('a', { 'class': 'tooltip', href: destination }).update(text);
        $('wrapper').appendChild(newTip);
        Element.hide(newTip);
        new Effect.Appear(newTip, {duration: 0.5});

        var _parentOffset   = a.cumulativeOffset();
        var _parentSize     = a.getDimensions();
        var tipWidth        = newTip.getWidth();

        newTip.setStyle({
            top: (_parentOffset[1] + _parentSize.height - 20)+'px',
            left: (_parentOffset[0]+(_parentSize.width/2))-(tipWidth/2) +'px'
        });

        a.onmouseout = function(e) {
            if (!e) var e = window.event;
            var tg = (window.event) ? e.srcElement : e.target;
            if (tg.match('img')) {tg = tg.up('a');}
            hideTip(a, newTip, text);
        }
    }
}

function hideTip(a, activeTip, text) {
    a.setAttribute('title', text);
    activeTip.remove();
}

/*  ==========================================================================================================  */
/*  E-Card Switcher
/*  ==========================================================================================================  */

function setup_ecards() {
    var thumbs = $('ecards-box').select('ul a');
    thumbs.each(function(thumb) {thumb.onclick = function() {return false;}});
    thumbs.invoke('observe', 'click', ecardSwitch);
}

function ecardSwitch(event) {
    var imgContainer    = $('detailview');
    var imgUrl          = this.href;
    var headerContent   = this.getAttribute('title');
    var newEl           = new Element('img', {src: imgUrl }).hide();
    var ImgToHide       = imgContainer.firstDescendant('img');
    var headerEl        = $('ecards-box').firstDescendant('h3');
    var clearActive     = $$('#ecards-box ul a');

    clearActive.invoke('removeClassName', 'active');
    this.addClassName('active');
  
    headerEl.update(headerContent);
    imgContainer.insert(newEl);
    new Effect.Fade(ImgToHide);
    new Effect.Appear(newEl);

    var imageId = this.previous().getValue();
    $('card_image_id').value= imageId;
    $$('.vorschauButton').each(function(elem) {
       elem.hide() });
    $('vorschau_' + imageId).toggle();

    var imageUrl = this.previous(1).getValue();
    $('image_url').value= imageUrl;
    $('input_bild_id').value= imageId;

}

/*  ==========================================================================================================  */
/*  Configure Shadowbox
/*  ==========================================================================================================  */

//  For the Contactforms:

//by ONSE

function runJavaScripts() {
    var shadowbox = $('sb-container');
    if (shadowbox.c1ready)
        return;

    var scripts = new Array();
    scripts = shadowbox.getElementsByTagName('script');

    for (i = 0; i < scripts.length; i++) {
        if (scripts[i].getAttribute('type') == 'text/javascript') {
            eval(scripts[i].innerHTML);
        }
    }
    shadowbox.c1ready = true;
}

function setShadowbox() {
    Shadowbox.setup($$('a.sbox'), {
        height: 550,
        width: 720,
        onFinish: runJavaScripts
    });

}


/*  ==========================================================================================================  */
/*  SWFObject // Videotrailer
/*  ==========================================================================================================  */

function setup_swfobject() {
    var flashContainer = $('flashcontent');

    // disable noscript warning
    flashContainer.select('p.noscript')[0].hide();
    var prev_img    = flashContainer.select('img')[0];

    var imgSource   = prev_img.getAttribute('src');
    var fileSource  = flashContainer.select('a')[0].getAttribute('href');
    var el_width    = prev_img.getAttribute('width');
    var el_height   = prev_img.getAttribute('height');

    var flashvars = {
      'image': imgSource,
      'file': fileSource,
      'width': el_width,
      'height': el_height
      // 'displayheight': 240
    }
    if (!(swfobject.hasFlashPlayerVersion("9.0.0"))) {
        // Show noflash warning
        flashContainer.select('p.noflash')[0].show();
    }

    swfobject.embedSWF("/swf/flvplayer.swf", "flashcontent", el_width, el_height, "9.0.0", false, flashvars);
}

/*  ==========================================================================================================  */
/*  Textarea Character Counter
/*  ==========================================================================================================  */

var TextCounter = Class.create({

    _counter: '',
    _maximum: 400,

    initialize: function(obj) {
        this.getMaximum(obj);
        _counter = obj.up().select('.counter')[0];
        obj.observe('keyup', this.counter.bindAsEventListener(obj));
    },
    
    getMaximum: function(obj) {
        var classNames = obj.classNames().inspect();
        if (classNames.indexOf('limited-') != -1) {
            _maximum = parseInt(classNames.split('-')[1]);
        }
        return _maximum;
    },

    counter: function() {
        var current_size    = this.value.length;
        var chars_left      = _maximum - current_size;

        if (chars_left >= 0) {
            _counter.update('(noch '+chars_left+' Zeichen)');
        } else {
            this.value = this.value.slice(0, _maximum);
        }
    }
});

/*  ==========================================================================================================  */
/*  Smooth Scrolling
/*  ==========================================================================================================  */

    function setup_smoothScrolling() {
        var scrollLinks = $$('a[href^=#]');
        scrollLinks.each(function(link) {
            if (link.hash.substr(1) != '') {
                link.onclick = function(){return false;}
            }
        });
        scrollLinks.invoke('observe', 'click', smoothScrolling);
    }

    function smoothScrolling(event) {
        var target_id = this.hash.substr(1);
        if (target_id != '') { // could happen with the aweful href="#"...
            Effect.ScrollTo(target_id);
        }
    }

/*  ==========================================================================================================  */
/*  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";
      }
}

/*  ==========================================================================================================  */

function expand_collapse_menus(event) {
    var trigger = this;
    var target  = trigger.next('.expand-wrapper');

    if (target.style.display == 'none') {
        new Effect.BlindDown(target, {
            duration: 0.6,
            queue: { position: 'end', scope: 'anims', limit:1 }
        });
    } else {
        new Effect.BlindUp(target, {
            duration: 0.6,
            queue: { position: 'end', scope: 'anims', limit:1 }
        });
    }
    trigger.toggleClassName('open');
}

/*  ==========================================================================================================  */

function init() {
    //Alle Vorschaubutton ausser dem aktiven verstecken.
    $$('.vorschauButton').each(function(elem) { 
       if(!elem.id.endsWith($F('card_image_id'))) {
          elem.hide() 
       }
    });

    // Input field value toggle
    init_input_toggle()
    // Smooth Scrolling
    setup_smoothScrolling();
    // Product Slider
    if ($$('.slider').size() >= 1) {
        $$('.slider').each(function(box) {
            new SlidingBox(box);
        });
        // Dont't show tooltips on Campus Studium Picture it
        if (!$('picture-it-slider')) {
            $$('.slider').invoke('observe', 'mouseover', showTip);
        }
    }
    // Mainteaser Fades
    if ($('mainteaser')) {
        var el = $('mainteaser');
        new FadingTeaser(el, 10);
    }
    // Expanding/Collapsing Boxes
    if ($$('.expandable').length >= 1) {
        $$('.expand-wrapper').invoke('hide');
        $$('.expandable').invoke('observe', 'click', expand_collapse_menus);
    }
    // Shadowbox
    if ($$('.sbox').size() >= 1) {
        setShadowbox();
    }
    // SWF Object and FLV Player
    if ($('flashcontent')) {
        setup_swfobject();
    }
    // E-Card Selector
    if ($('ecards-box')) {
        setup_ecards();
    }
    if ($$('textarea[class|=limited]').size() >= 1) {
        $$('textarea[class|=limited]').each(function(txtfield) {
            new TextCounter(txtfield);
        })
    }
    // External Links
    externalLinks();
    
    // Zahlmethode form toggle
    if ($$('.field .togglebox').length >= 1) {
        $$('.field li > input[type=radio]').each(function(radiobtn) {
            if (radiobtn.checked == false && radiobtn.up().next().hasClassName('togglebox')) {
                radiobtn.up().next().hide();
            }
        });
        if (!Prototype.Browser.IE) {
            $$('.field input[type=radio]').invoke('observe', 'change', toggleForms);
        } else {
            $$('.field input[type=radio]').invoke('observe', 'click', toggleForms);
        }
    }

}

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

