window.addEvent('domready',function(){
  _vdek._init();
});

function videoUrl(vipUrl) 
{
	// aktuelle Url um Bestandteile zu ermitteln
	// z.B. http://vstcmsentw01/VdAKInternet_edit/VdAKInternet/Service/Vorlagen/Pages/Video.jsp
	var aktUrl = document.URL;	
	
	// URL aufteilen
	// z.B. ../../../presse/video/video1.flv
	// oder presse/video1.flv
	var vipUrlSplit = vipUrl.split("/");
	var aktUrlSplit = aktUrl.split("/");
	
	var newUrl = '';
	var counter = 0;
	var gemeinsam ='';
	// ermitteln wie viele /../
	for (var i = 0; i < vipUrlSplit.length; i++)
	{
			var split = vipUrlSplit[i];
			if(split=='..')
				counter++;
			else
				gemeinsam = split;
	}
	// ermitteln des ersten Teils
	for (var i = 0; i < (aktUrlSplit.length-(counter+1)); i++)
	{
			newUrl = newUrl + aktUrlSplit[i] + '/';
	}
	// ermitteln des zweiten Teils
	for (var i = (counter); i< vipUrlSplit.length-1; i++)
	{
		  var split = vipUrlSplit[i]
		  if(split != gemeinsam)
				newUrl = newUrl + split + '/';
	}
	// anhänden des Dateinamens
	newUrl = newUrl + vipUrlSplit[vipUrlSplit.length-1];
	document.getElementById("video-with-unique-id").location = newUrl;
	if(typeof(newUrl) !== 'undefined' && newUrl != null)
		return newUrl;
	else
		return vipUrl;
};

/* Basic functions for measuring elements or output a debug window */
var _basics={_getBorderAndPadding:function(el){return{x:el.getStyle('paddingLeft').toInt()+el.getStyle('paddingRight').toInt()+el.getStyle('borderLeftWidth').toInt()+el.getStyle('borderRightWidth').toInt(),y:el.getStyle('paddingTop').toInt()+el.getStyle('paddingBottom').toInt()+el.getStyle('borderTopWidth').toInt()+el.getStyle('borderBottomWidth').toInt()}},getAbsoluteSize:function(el,debug){return{x:el.getSize().x-this._getBorderAndPadding(el).x,y:el.getSize().y-this._getBorderAndPadding(el).y}},getAbsoluteScrollSize:function(el){return{x:el.getScrollSize().x-this._getBorderAndPadding(el).x,y:el.getScrollSize().y-this._getBorderAndPadding(el).y}},debug:{win:null,msg:function(msg){this.init();this.win.set('html',msg)},init:function(){if(!this.win){this.win=new Element('div',{'style':'position:absolute;top:0;left:0;width:300px;z-index:99;background:#ff0000;color:#fff'}).inject($$('body')[0])}}}}

var _vdek = {
  /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     VDEK-Template-Scripts, V1 (2010-11-11) - post@thomasgoellner.de
     ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */

  // Alle Elemente, die runde Ecken erhalten sollen, werden hier deklariert,
  // mit id ($$-CSS-Selektor), c (Art der Ecken, tl, tr, br, bl), b (mit 1px border oder nicht)
  elements_with_borders : new Array(
                            {id:'.blue-rounded-box',c:['tl','tr','bl','br'],b:false},
                            {id:'.blue-rounded-box .rounded',c:['tl','tr','bl','br'],b:false},
                            {id:'.blue-rounded-boxinhalt',c:['tl','tr','bl','br'],b:false},
                            {id:'.blue-rounded-boxinhalt .rounded',c:['tl','tr','bl','br'],b:false},                            
                            {id:'#column-left table tr:first-child th:first-child',c:['tl'],b:false},
                            {id:'#column-left table tr:first-child th:last-child',c:['tr'],b:false},                            
                            {id:'button.submit',c:['bl','br'],b:false},
                            {id:'.videobox',c:['tl','tr'],b:false},
                            {id:'#header-image .rounded',c:['tr','br'],b:false},
                            {id:'.rounded-image .rounded',c:['tl','tr','br','bl'],b:true},             
                            {id:'.form-container h2',c:['tl','tr'],b:false},
                            {id:'.search-container h2',c:['tl','tr'],b:false}
                          ),

  _init : function()
  {
    this._slideshow_init();
    this._maps_init();
    this._mediaplayer_init();
    this._equal_content_columns();

    // Alle .blue-rounded-box- und #header-image untersuchen und sofern darin Bilder
    // enthalten sind, ein SPAN.rounded herumlegen, damit dieses mit runden Ecken gestylt werden kann
    // add rounded corners to all images contained in h1.header-image
      $$('.blue-rounded-box').combine($$('#header-image')).combine($$('.rounded-image')).each(function(el,i){
      //$$('#header-image').combine($$('.rounded-image')).each(function(el,i){
      if(el.getElement('img'))
      {
        new Element("span", {"class": "rounded",
            styles: {
                "background-image": "url(" + el.getElement('img').getProperty('src') + ")",
                height: el.getElement('img').getProperty('height') + "px",
                width: el.getElement('img').getProperty('width') + "px"
            }
        }).wraps(el.getElement('img'));
      }
    });

    // Sofern IE-Browser, behandele alle gefundenen Elemente die auf die angegebenen
    // elements_with_borders passen so, dass innerhalb des Elements fuer jede runde
    // Ecke ein span mit entsprechender Klasse hinzugefügt wird. Darauf achten, dass
    // dieses Element auch eine position:-Angabe besitzt
    if(Browser.ie || Browser.firefox2)
    {
      for(i=0; i<this.elements_with_borders.length; i++)
      {
        if($$(this.elements_with_borders[i].id).length>0)
        {
          for(j=0; j<this.elements_with_borders[i].c.length; j++)
          {
            $$(this.elements_with_borders[i].id).each(function(el){
              new Element('span.rc'+(this.elements_with_borders[i].b ? '.wb' : '')+'.'+this.elements_with_borders[i].c[j]).inject(el);
            }.bind(this));
          }
        }
      }    
    }
  },
    
  _slideshow_init : function(){
    // Untersuche das Dokument nach .slideshow-container-Elementen und 
    // initialisiere ggf. ein neues Slideshow-Objekt dafür (_vdek._slideshow)
    $$('.slideshow-container').each(function(ss,i){
      if(tmp = this._slideshow(ss)){ if(tmp.init) ss.slideshow = tmp.init(); delete tmp; }
    }.bind(this));
  },
  
  _maps_init : function() {
    // Untersuche das Dokument nach .map-container-Elementen und 
    // erweitere die Links um MOUSEOVER-Funktionen zur Anzeige
    // des Bundeslandes
    $$('.map-container').each(function(mc,i){
      if(mc.getElement('.map') && mc.getElement('.text'))
      {
        if(mc.getElement('.text').getElements('.map-link'))
        {
          mc.getElement('.map').standardClass = mc.getElement('.map').get('class');
          
          mc.getElement('.text').getElements('.map-link').each(function(link,i){
            cls = link.get('class').replace('map-link','').trim();
            if(cls!='')
            {
              cls = cls.indexOf(' ')>-1 ? cls.split(' ') : new Array(cls);
              link.theClass = 'map-'+cls[0];
              link.addEvents({
                'mouseenter' : function(){
                  this.getParent('.map-container').getElement('.map').set('class',this.getParent('.map-container').getElement('.map').standardClass);
                  this.getParent('.map-container').getElement('.map').addClass(this.theClass);
                },
                'mouseleave' : function(){
                  this.getParent('.map-container').getElement('.map').set('class',this.getParent('.map-container').getElement('.map').standardClass);
                }
              });
            }
          });
        }        
      }
    }.bind(this));
  },
  
  _mediaplayer_init : function() {
    $$('.mediaplayer').each(function(media,i){
      if(media.get('href'))
      {
      	var vidurl = videoUrl(media.get('href'));
      	
        ext = media.get('href').substr(media.get('href').lastIndexOf('.')+1).toLowerCase();
        switch(ext)
        {
          case 'flv' :
          case 'f4v' :
          case 'mov' :
          case 'mp4' :
            height = 220;
          break;
          case 'mp3' :
          case 'aac' :
            height = 20;
          break;
        }
        
        if(typeOf(height)=='number')
        {
          if(media.getElement('img')) media.getElement('img').clone(1,1).addClass('printonly').inject(media,'after');
                    
          options = {
            id : 'swiff_'+media.get('id'),
            container : new Element('div#'+media.get('id')+'.videobox').replaces(media),
            width  : '100%',
            height : height,
            params : {
              wmode:'opaque',
              allowScriptAccess: true,
              quality:'high',
              bgcolor:'ffffff',
              allowFullScreen:true,
              debug:true,
              stretching:'uniform'
            },
            vars : {
              // funktioniert nicht mit relativ-übergebenen Urls    
              //file : media.get('href'),
              // funktioniert im Firefox - nicht im IE6
              //file : media,
              // selbstentwickelte Funktion für die URL-Übersetzung              
              // stretching: fill, uniform, exactfit, none
              file : vidurl,
              image : media.getElement('img') ? media.getElement('img').get('src') : '',
              skin : '../../../../../../../../../../../_jwplayer/vdek.zip',
              autostart:false,
              stretching:'uniform',
              fullscreen:true,
              debug:true
            },
            properties:{tmp:'0'}
          };
          new Swiff('../../../../../../../../../../../_jwplayer/flv-player.swf',options);
          // Achtung die Pfade verweisen auf den Wurzelpfad des Webservers
          // Da dieser jedoch nicht bekannt ist, werden pauschal Ebenen-Sprünge nach oben gesetzt
          // Falls ein Video in einem unteren Pfad nicht funktioniert, müssen Ebenen ergänzt werden
          // Wiedenfeld
        } 
      }
    }.bind(this));
  },
  
  _equal_content_columns : function() {
    cols = $$('#column-left').combine($$('#column-right'));
    h = 0;
    for(i=0; i<cols.length; i++)
      if(cols[i].getSize(cols[i]).y > h) h = cols[i].getSize(cols[i]).y;
    
    for(i=0; i<cols.length; i++)
      cols[i].setStyle('height',h+'px');
  },
  
  _slideshow : function(ss){
    if(typeOf(ss)=='element')
    {
      if(ss.getElement('.thumbnails'))
      {
        if(ss.getElement('.thumbnails').getElements('.thumbnail'))
        {
          return {
            thumbnailContainer : ss.getElement('.thumbnails'),
            thumbnails : ss.getElement('.thumbnails').getElements('.thumbnail'),
            ss : ss,
            effect : 'slide',
            cur_item  : -1,
            new_item  : 0,
            is_moving : false,
            duration  : 200,
            transition : Fx.Transitions.Quad.easeInOut,
            init      : function() {
              this.stage = new Element('div.stage').inject(this.thumbnailContainer,'before');
              
              controls = new Element('div.controls').wraps(ss.getElement('.thumbnails'));
              posx = 0;
              for(j=0; j<this.thumbnails.length; j++)
              {
                link = this.thumbnails[j];
                link.setStyles({
                  'position':'absolute',
                  'top':0,
                  'left':posx+'px'
                });
                posx+=_basics.getAbsoluteSize(link).x + 10;
                
                link.set('rel','');
                if(link.get('title')!=null)
                {
                  link.set('rel',link.get('title'));
                }
                else if(link.getElement('img'))
                {
                  if(link.getElement('img').get('alt')!=null)
                    link.set('rel',link.getElement('img').get('alt'));

                }
                
                if(link.get('title')!=null) link.set('title','');
                if(link.getElement('img')!=null) link.getElement('img').set('alt','');
                
                link.itemid = j;
                link.addEvent('click',function(){
                  obj.load(this.itemid);
                  return false;
                }.pass([obj = this],link))
              }
              this.slider = new _slider(this.thumbnailContainer,controls,{sliderwidth:posx-10});
              
              this.load(0);
              
              return this;
            },
            updateText : function() {
              // update titles / img description
              if(!this.description) this.description = new Element('div.description').inject(this.stage,'top');
              this.description.empty();

              if(this.thumbnails[this.new_item].get('rel')!='') this.description.set('html',this.thumbnails[this.new_item].get('rel'));
            },
            update : function()
            {
              this.updateText();
              
              // css-classes
              this.cur_item = this.new_item;
              this.new_item = null;
              this.is_moving = false;
            },
            next      : function() { 
              if(this.cur_item < this.items.length-1)
                this.load(this.cur_item+1);
            },
            prev      : function() {
              if(this.cur_item > 0)
                this.load(this.cur_item-1);
            },
            load  : function(num){
              num = typeof num != 'undefined' ? num.toInt() : -1;

              if(!this.is_moving && num>-1 && num < this.thumbnails.length && num != this.cur_item)
              { 
                this.is_moving = true;
                this.new_item = num;

                this.thumbnailContainer.getElements('.thumbnail').removeClass('active');
                this.thumbnailContainer.getElements('.thumbnail')[this.new_item].addClass('active');
                
                this.fadeout(function(){
                  if(!this.thumbnails[this.new_item].image)
                  {
                    this.thumbnails[this.new_item].image = new Asset.image(this.thumbnails[this.new_item].get('href'), {
                      onLoad: function(){
                        this.show(num);
                      }.pass([num],this)
                    });
                  }
                  else
                    this.show(num);
                }.bind(this));  
              }
            },
            fadeout : function(oc)
            {
              oc = typeOf(oc) == 'function' ? oc : function(){};
              
              if(this.thumbnails[this.cur_item])
              {
                if(this.thumbnails[this.cur_item].image)
                {
                  new Fx.Morph(this.thumbnails[this.cur_item].image,{
                    duration: this.duration,
                    transition : this.transition,
                    onComplete : function()
                    {
                      this.thumbnails[this.cur_item].image.dispose();
                    }.bind(this)
                  })
                  .start({
                    'opacity':[this.thumbnails[this.cur_item].image.getStyle('opacity').toInt(),0]
                  })
                  .chain(oc);
                }
                else
                  oc();
              }
              else
                oc();
            },
            
            show : function() {
              this.thumbnails[this.new_item].image
              .setStyles({
                'position':'absolute',
                'top':'0', 'left':'50%',
                'opacity':'0'
              })
              .inject(this.stage);
              
              this.thumbnails[this.new_item].image.setStyles({
//                  'margin-top':Math.ceil(this.thumbnails[this.new_item].image.getSize().y/-2),
                'margin-left':Math.ceil(this.thumbnails[this.new_item].image.getSize().x/-2)
              });

              new Fx.Morph(this.thumbnails[this.new_item].image,{
                duration: this.duration,
                transition : this.transition,
                onComplete : function()
                {
                  this.update();
                }.bind(this)
              })
              .start({
                'opacity':[this.thumbnails[this.new_item].image.getStyle('opacity').toInt(),1]
              });
            }
          }
        }
      }
    }
    return false;
  }
}


var _slider = new Class({
  /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     Slider - arrangiert die Kind-Elemente eines Elements nebeneinander
     und fuegt daraufhin VOR- und ZURUECK-Pfeile ein
     ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
  getOptions: function(){
		return {
			speed : Browser.ie ? 200 : 100,
			width : null,
			maximum : 0,
			minimum : null,
			debug : false,
			sliderwidth : null
		};
	},
	
	setOptions: function(defaultOptions, options)
	{
	  for (var i in defaultOptions)
	   defaultOptions[i] = typeof options[i]!='undefined' ? options[i] : defaultOptions[i];
	  
	  this.options = defaultOptions;
    
    delete i,defaultOptions,options;
    
    return this.options;	
  },
   
  initialize: function(container,controlContainer,options)
  {
		this.setOptions(this.getOptions(), options);
		this.container = typeOf(container) == 'string' ? $(''+container) : container;

		if(this.container)
		{
		  if(this.options.width==null) this.options.width = this.container.getSize().x;
		  if(this.options.sliderwidth==null) this.options.sliderwidth = this.container.getStyle('width').toInt();
 
      if(this.options.sliderwidth > this.options.width)
      { 
        left = isNaN(this.container.getStyle('left').toInt()) ? '0px' : this.container.getStyle('left');
        
        this.slider = new Element('div',{
          'class' : 'slider'
        })
        .setStyles({
          'position':'absolute',
          'left':left
        });
        this.container.getChildren().each(function(el){
          el.clone().cloneEvents(el).inject(this.slider)
        }.bind(this));
        this.slider.inject(this.container.empty());
        
        if(!this.options.minimum) this.options.minimum = this.options.width - this.options.sliderwidth;

  		  this.controlContainer = typeOf(controlContainer) == 'string' ? $(''+controlContainer) : controlContainer;
        if(!this.controlContainer)
  		    this.controlContainer = this.container;
  		  
    		this.gotoX = 0;
    		this.direction = 0;
    		this.interval = null;
    		this.insertButtons();
      }
    }
  },
  
  doSlide : function(tox)
  {
    if(this.direction!=0 || tox!=0)
    {
      if(tox.toInt()!=0) alert(tox);
      this.gotoX = this.slider.getStyle('left').toInt() + this.direction*this.options.speed;
  
      this.prevButton.removeClass('inactive');
      this.nextButton.removeClass('inactive');

      if(this.gotoX < this.options.minimum)
      {
        this.gotoX = this.options.minimum;
        this.direction = 0;
        this.nextButton.addClass('inactive');
      }
      else if(this.gotoX >this.options. maximum)
      {        
        this.gotoX = this.options.maximum; 
        this.direction;
        this.prevButton.addClass('inactive');
      }
    }
    this.gotoX = Math.round(this.gotoX);
    
    step = (this.gotoX - this.slider.getStyle('left').toInt()) / 10;
    step = step < 0 ? Math.floor(step) : Math.ceil(step);

    if(this.options.debug)
    {
      _basics.debug.msg(
        this.slider.getStyle('left').toInt()+' (wo) + ' + step + ' = (to)  '+this.gotoX+'<br />'+
        this.options.width + ' - ' + this.options.sliderwidth + ' = ' + (this.options.width - this.options.sliderwidth)
      );
    }
        
    if(step==0) this.stop();
    else this.slider.setStyle('left',(this.slider.getStyle('left').toInt()+step)+'px');
    
    delete step;
  },
    
  stop : function()
  {
    clearInterval(this.interval);
    this.direction = 0;
    this.slider.setStyle('left',this.gotoX+'px');
  },
  
  slide : function(dir)
  {
    clearInterval(this.interval);
    this.direction = dir*-1;
    this.interval = this.doSlide.periodical(10,this,0);
  },
  
  slideTo : function(pos)
  {    
    clearInterval(this.interval);
    this.interval = this.doSlide.periodical(10,this,pos);
  },
  
  insertButtons : function()
  {
    if(!this.prevButton)
    {
      this.prevButton = new Element('a',{
        'class' : 'slider-back',
        'href' : 'javascript:void(0)'
      })
      .inject(this.controlContainer)
      .addEvents({
        'mousedown' : function(e){ this.prevButton.addClass('active'); this.slide(-1); }.bind(this),
        'mouseup'   : function(e){ this.prevButton.removeClass('active'); this.slide(0); }.bind(this),
        'mouseleave': function(e){ this.prevButton.removeClass('active'); if(this.interval) this.slide(0); }.bind(this)
      });
    }

    if(!this.nextButton)
    {
      this.nextButton = new Element('a',{
        'class' : 'slider-forward',
        'href' : 'javascript:void(0)'
      })
      .inject(this.controlContainer)
      .addEvents({
        'mousedown' : function(e){ this.nextButton.addClass('active'); this.slide(1); }.bind(this),
        'mouseup'   : function(e){ this.nextButton.removeClass('active'); this.slide(0); }.bind(this),
        'mouseleave': function(e){ this.nextButton.removeClass('active'); if(this.interval) this.slide(0); }.bind(this)
      });
    }
    
    this.prevButton.removeClass('inactive');
    this.nextButton.removeClass('inactive');
    if(this.slider.getStyle('left').toInt()>=this.options.maximum) this.prevButton.addClass('inactive'); else this.prevButton.removeClass('inactive');
    if(this.slider.getStyle('left').toInt()<=this.options.minimum) this.nextButton.addClass('inactive'); else this.nextButton.removeClass('inactive');
  }
});



