var hasEvent = function(el,eventType,fn)
{
  if($type(el)=='element')
  {
		var myEvents = el.retrieve('events');
		//can we shoot this down?
		return myEvents && myEvents[eventType] && (fn == undefined || myEvents[eventType].keys.contains(fn));
  }
}

var multibox = null;

var _content_loader = {
  isloading : false,
  objects: new Object(),
  newContentObj: null,
  curContentObj: null,
  
  duration : 400,
  transition : Fx.Transitions.Sine.easeOut,
  
  fxchain : new Chain,

  menulevels : 4,
  level_to_hide : 0,
  
  currentMap : null,

  
  init : function(){
    if(Browser.Engine.trident && Browser.Engine.version<=4)
      return false;
    
    this.createLinks($$('body')[0]);
    
    if($chk(CUR_OBJ))
      this.objects[CUR_OBJ.article_id] = this.newContentObj = this.curContentObj = CUR_OBJ;
    this.server = SERVER;
    
    if(Browser.Engine.trident)
      $$('a').addEvent('focus',function(){this.blur();});

    $('content').setStyles({
      'height':_basics.getAbsoluteSize($('content')).y+'px',
      'overflow':'hidden'
    });
    
    this.contentPadding = _basics.getAbsoluteSize($('content')).y - this.getContentHeight();
    
    this.loaderOff();
  },
  
  getContentHeight : function()
  {
    cntHeight = _basics.getAbsoluteSize($('content').getElement('.left')).y;
    if(_basics.getAbsoluteSize($('content').getElement('.right')).y > cntHeight)
      cntHeight = _basics.getAbsoluteSize($('content').getElement('.right')).y;
    
    return cntHeight;
  },
   
  
  getObjectByHref : function(href)
  {
    for(var i in this.objects)
      if(this.objects[i].href == href)
        return this.objects[i];
    
    return false;
  },
  
  load : function(url)
  {
    if(url != this.curContentObj.href)
    {
      this.loaderOn();
      if(!$chk(this.newContentObj = this.getObjectByHref(url)))
      {
        // load the new object
        link = url+(url.indexOf('?')>-1 ? '&' : '?')+'json=1';
        new Request.JSON({url: link,
          onComplete: function(obj){
            if($chk(obj))
              this.objects[obj.article_id] = this.newContentObj = obj;
            else
              this.newContentObj = this.curContentObj;

            this.switchContent();
          }.bind(this)
        }).get();
      }
      else
        this.switchContent();
    }
  },
  
  switchContent: function()
  {
    this.fxchain.clearChain();
    
    this.fxchain.chain(function(){this.updateLinkClasses();}.bind(this));

    // content ausblenden
    this.fxchain.chain(function(){this.hideContent();}.bind(this));
    
    // headergrafiken ausblenden und neu einblenden (sofern diese sich von den neuen unterscheiden)
    if(this.newContentObj.header != this.curContentObj.header)
    {
      this.fxchain.chain(function(){this.hideHeader();}.bind(this));
      this.fxchain.chain(function(){this.showHeader();}.bind(this));
    }
    
    // content einsetzen
    this.fxchain.chain(function(){this.insertContent();}.bind(this));
    
    // seite resizen
    this.fxchain.chain(function(){this.resizePage();}.bind(this));
    
    // content einblenden
    this.fxchain.chain(function(){this.showContent();}.bind(this));
    
    // finish loading
    this.fxchain.chain(function(){this.finishLoading();}.bind(this));
    
    // execute the chain
    this.doChain();
  },
  
  updateLinkClasses : function()
  {
    $$('.rex-active').removeClass('rex-active');              
    if(this.newContentObj.pathurls)
    {
      urls = this.newContentObj.pathurls.indexOf('|')>-1 ? this.newContentObj.pathurls.split('|') : [this.newContentObj.pathurls];
      for(i=0; i<urls.length; i++)
      {
        $$('a[href='+urls[i]+']').addClass('rex-active');
        if($$('a[href='+urls[i]+']').getParent())
          if($$('a[href='+urls[i]+']').getParent().get('tag')=='li')
            $$('a[href='+urls[i]+']').getParent().addClass('rex-active');
      }
    }
    $$('a[href='+this.newContentObj.href+']').addClass('rex-active');
    
    this.doChain();
  },
  
  hideContent : function()
  {
    new Fx.Morph(
      $('content'),
      {
        duration: this.duration,
        transition: this.transition,
        onComplete: function()
        {
          this.oldsize = this.getContentHeight();
          
//          this.objects[this.curContentObj.article_id].cnt_col1 = $('content').getElement('.left').get('html');
//          this.objects[this.curContentObj.article_id].cnt_col2 = $('content').getElement('.right').get('html');
          
          $empty($('content').getElement('.left'));
          $empty($('content').getElement('.right'));
          
          $('content').removeClass('cnt_home'); if(this.newContentObj.bodyid=='home') $('content').addClass('cnt_home');            
          
          $('content').getElement('.left').setStyles({'overflow':'visible','height':'auto'});
          $('content').getElement('.right').setStyles({'overflow':'visible','height':'auto'});
          this.doChain();
        }.bind(this)
      }
    )
    .start({
      'opacity':[$('content').getStyle('opacity'),0]
    });
  },
  
  hideHeader : function()
  {
    if($('header').get('html')!='')
    {
      new Fx.Morph(
        $('header'),
        {
          duration: this.duration/2,
          transition: this.transition,
          onComplete: function()
          {
            $empty($('header'));
            $('header').set('html',this.newContentObj.header);
            this.doChain();
          }.bind(this)
        }
      )
      .start({
        'opacity':[$('header').getStyle('opacity'),0]
      });  
    }
    else
    {
      $('header').setStyle('opacity',0);
      $('header').set('html',this.newContentObj.header);
      this.doChain();
    }
  },
  
  showHeader : function()
  {
    if($('header').get('html')!='')
    {
      new Fx.Morph(
        $('header'),
        {
          duration: this.duration/2,
          transition: this.transition,
          onComplete: function()
          {
            this.doChain();
          }.bind(this)
        }
      )
      .start({
        'opacity':[$('header').getStyle('opacity'),1]
      });  
    }
    else
    {
      $('header').setStyle('opacity',1);
      this.doChain();
    }
  },
  
  insertContent : function()
  {
    $('content').getElement('.left').set('html',this.newContentObj.cnt_col1);
    $('content').getElement('.right').set('html',this.newContentObj.cnt_col2);
    
    this.executeJS();

    this.createLinks($('content'));

    this.newsize = this.getContentHeight();

    this.doChain();
  },
  
  resizePage : function()
  {
    
    resize = function(){
      new Fx.Morph(
        $('content'),
        {
          duration: _content_loader.duration/2,
          transition: _content_loader.transition,
          onComplete : function()
          {
            this.doChain();
          }.bind(this)
        }
      )
      .start({
        'height':[$('content').getStyle('height').toInt(),this.newsize+this.contentPadding]
      });        
    }.bind(this);
  
    // nach oben scrollen, weil der neue content kleiner ist als der alte 
    // gotoY = ($$('body')[0].getScrollSize().y-this.oldsize)+this.newsize < window.getSize().y  ? 0 : $('content').getPosition($$('body')[0]).y;
    gotoY = 30;

    if(this.oldsize > this.newsize && $$('body')[0].getScroll().y>gotoY)
    {
      
      new Fx.Scroll($$('body')[0], {
        duration: this.duration,
        transition: Fx.Transitions.Sine.easeOut
      }).start($$('body')[0].getScroll().y, gotoY)
      .chain(resize);
    }
    else
      resize();
  },
  
  showContent : function()
  {
    new Fx.Morph(
      $('content'),
      {
        duration: this.duration,
        transition: this.transition,
        onComplete: function()
        {
          this.doChain();
        }.bind(this)
      }
    )
    .start({
      'opacity':[$('content').getStyle('opacity'),1]
    });
  },
  
  executeJS : function()
  {
    _bandmembers.init();
    _niftyPlayer.addSingleTrackPlayer($('content'));
    if($chk($('image_slideshow_0')) && $chk($$('.image_slideshow_thumbs_0')))
      new SlideShow('image_slideshow_0','image_slideshow_thumbs_0',{wait:15000,duration:3000,effect:'fade',thumbnails:true,autoplay:true,loop:true}).play(1);

    if(!Browser.Engine.trident)
    {
      // each video will stop the mp3-palyer if touched by the mouse
      $$('object').each(function(el,index){
        if(!$chk(el.get('id')))
          el.set('id','flashobject_'+index);
        
        if($chk(movie = el.getElement('param[name*=movie]')))
        {
          if($chk(movie = movie.get('value')))
          {
            if(movie.indexOf('youtube')>-1 || movie.indexOf('vimeo')>-1)
              el.addEvent('mouseenter',function(){
                if($chk(_niftyPlayer.currentSingleTrack) && _niftyPlayer.getState()=='playing')
                  _niftyPlayer.stop();
              });
          }
        }
      });
    }
    
    $$('.video').each(function(el,index){
      if($chk(id = el.getElement('div').get('id')))
      { 
        if(id.indexOf('flashobject')>-1)
        {
          new Swiff(TEMPLATE_DIR+'../addons/admintools/flash/jwplayer/flv-player.swf',
          {
            id:'swiff_'+id,
            width:440,height:300,
            container:el,
            params:{
              wmode:'opaque',
              allowScriptAccess:true,
              quality:'high',
              bgcolor:'000',
              allowFullScreen:true
            },
            vars:{
              file:el.getElement('a').get('href'),
              image:($chk(el.getElement('img')) ? el.getElement('img').get('src') : ''),
              icons:false,
              backcolor:'333333',
              frontcolor:'cccccc',
              lightcolor:'ffffff',
              dock:false,
              skin:TEMPLATE_DIR+'../addons/admintools/flash/jwplayer/modieus.swf',
              controlbar:'over',
              autostart:false,
              stretching:'fill',
              fullscreen:true
            },
            properties:{
              tmp:'0'
            }
          });
        }
      }
    });
    
    multibox = null;
    
    $$('.images').each(function(el,index){
      if(el.getElements('a'))
      {
        cls = '';
        for(i=0; i<el.getElements('a').length; i++)
        {
          if(el.getElements('a')[i].get('class') && el.getElements('a')[i].get('class')!=cls)
          {
            cls = el.getElements('a')[i].get('class');
            if(!multibox) multibox = {};
            multibox[cls] = new MultiBox(cls,{
              path:'http://preview.pentatones.de/files/addons/admintools/',
              skin:'http://preview.pentatones.de/files/addons/admintools/flash/jwplayer/modieus.swf',
              name:cls
            });
          }
        }
        multibox = null;
      }
    });
    
  },
    
  finishLoading : function()
  {
    this.curContentObj = this.newContentObj;
    this.newContentObj = null;
    this.loaderOff();
  },
  
  loaderOn : function()
  {
    this.isloading = true;
    if(!$chk($('loader')))
    {
      new Element('div',{
        'id':'loader'
      })
      .setStyle('z-index','99')
      .inject($('page'),'top');
    }
    
    if(_niftyPlayer.obj != null && $$('#content .niftyplayer-singletrack.playing').length>0)
    {
      _niftyPlayer.pause();  
    }
  },
  loaderOff : function()
  {
    this.isloading = false;
    if($chk($('loader')))
    {
      $('loader').destroy();      
    }
    
  },
  
  createLinks : function(box)
  {
    if($chk($(box)))
    { 
      // links = $(box).getElements('a[href=^/]').combine($(box).getElements('a[href*=preview.pentatones.de]'));
      links = $(box).getElements('a[href^=/]');
      links.each(function(link)
      { 
        if($chk(link) && $chk(linkhref = link.get('href')) && !link.getParent('ul.nav-lang'))
        { 
          if(link.get('href').indexOf(window.location.host)>-1)
            linkhref = link.get('href').split(window.location.host)[1];

          if(!hasEvent(link,'click') && linkhref.indexOf('files/')<=-1 && linkhref.indexOf('#')<=-1 && linkhref.indexOf('javascript')!=0 && linkhref.indexOf('mailto')!=0 && linkhref.indexOf('rr-')!=0)
          { 
            link.set('rel',linkhref);
            
            link.addEvent('click',function(){
              _content_loader.load(this.get('rel'));
              return false;
            });
            if(Browser.Engine.trident)
              link.addEvent('focus',function(){this.blur();});
          }
        }
      });
    }
  },
  
  
  showContentBackground : function(to)
  {
    if($chk(bg = $('content-bg')))
    {
      if(!$chk(to))
        to = $('content').getSize().x;
      else
        to+=20; // add the padding to the new width

      if($chk(bg.effect)) bg.effect.cancel();
      bg.effect = new Fx.Morph(
        bg,
        {
          duration: this.duration,
          transition: this.transition
        }
      )
      .start({
        'width':[bg.getSize().x,to],
        'left':[bg.getPosition('page').x,0]
      });
    }
  },

  hideContentBackground : function()
  {
    if($chk(bg = $('content-bg')))
    {
      if($chk(bg.effect)) bg.effect.cancel();
      bg.effect = new Fx.Morph(
        bg,
        {
          duration: this.duration,
          transition: this.transition
        }
      )
      .start({
        'left':[bg.getPosition('page').x,bg.getSize().x*-1]
      });
    }
  },



  
  doChain : function()
  {
    this.fxchain.callChain();
  }
};


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(!$chk(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 _OLD_bandmembers = {
  members : null,
  currentMember : 0,
  isloading : false,
  fxchain : new Chain(),
  duration : (Browser.Engine.gecko ? 300 : 200),
  transition : Fx.Transitions.Sine.easeOut,
  
  menuHeight : 120,
    
  init : function()
  {
    if($chk(this.members = $$('.band-member')) && this.members.length>0)
    {
      this.container = this.members[0].getParent('div');

      this.maxheight = this.members[0].getSize().y;
      this.padding = this.container.getParent('div').getSize().y;

      this.menu = new Element('div', {
        'class':'band-members-menu'
      })
      .inject(this.container,'after');

      this.members.each(function(member,index){
        if(this.maxheight < member.getSize().y)
          this.maxHeight = member.getSize().y;
        
        this.padding-=member.getSize().y;
        
        new Element('a',{
          'id':'btn-'+member.get('id'),
          'href':'javascript:void(0)'
        })
        .set('html',member.get('id'))
        .addEvent('click',function(){
          this.showMember(index);
        }.bind(this))
        .inject(this.menu);
          
      }.bind(this));
      
      this.container.setStyles({
        'overflow':'hidden',
        'height':this.members[0].getSize().y
      });

//      alert(this.container.getParent('div').get('class'));
      this.container.getParent('div').setStyles({
        'overflow':'hidden',
        'height':this.maxHeight+this.padding+this.menuHeight
      });

      this.members.setStyles({'display':'none'});
      this.members[0].setStyles({'display':'block'});
      this.menu.getElements('a')[0].addClass('active');
      
    }
  },
  
  showMember : function(index)
  {
    if(index!=this.currentMember)
    {
      this.isloading = true;
      this.newMember = index;
      
      this.menu.getElements('a')[this.currentMember].removeClass('active');
      this.menu.getElements('a')[this.newMember].addClass('active');

      new Fx.Morph(this.members[this.currentMember],{
        duration: this.duration,
        transition: this.transition,
        onComplete: function(){
          from = this.members[this.currentMember].getSize().y;
          
          this.members[this.currentMember].setStyles({
            'display':'none',
            'opacity':1
          });
          
          this.members[this.newMember].setStyles({
            'display':'block',
            'opacity':0
          });
          to = this.members[this.newMember].getSize().y;
          
          new Fx.Morph(this.container,{
            duration: this.duration,
            transition: this.transition,
            onComplete: function(){
              
              new Fx.Morph(this.members[this.newMember],{
                duration: this.duration,
                transition: this.transition,
                onComplete: function(){
                  this.isloading = false;
                  this.currentMember = this.newMember;
                  
                }.bind(this)
              })
              .start({
                'opacity':[this.members[this.newMember].getStyle('opacity'),1]
              });
              
            }.bind(this)
          })
          .start({
            'height':[from, to]
          });
        }.bind(this)
      })
      .start({
        'opacity':[this.members[this.currentMember].getStyle('opacity'),0]
      });
    }
  },
  
  doChain : function()
  {
    this.fxchain.callChain();
  }
}


var _bandmembers = {
  view : function(memberbox) {
    if($type(memberbox) == 'element')
    {
      contents = memberbox.getElements('.contents .member-content');
      links = memberbox.getElements('.links .member-link');
      names = memberbox.getElements('.names .member-name');
      
      if(contents.length == links.length && contents.length==names.length)
      {
        return {
          box : memberbox,
          contents : contents,
          otherctypes : [],
          boxheight : 0,
          links : links,
          names : names,
          
          isloading : false,
          cur_item : -1,
          fxchain : new Chain(),
          duration : (Browser.Engine.gecko ? 300 : 200),
          transition : Fx.Transitions.Sine.easeOut,
          
          init : function()
          {
            for(i=0; i<this.contents.length; i++)
            {
              this.links[i].set('rel',i);
              this.links[i].removeEvents('click');
              this.links[i].addEvents({
                'mouseenter' : function(){ obj.dohover(this.get('rel')); }.pass([obj = this],this.links[i]),
                'mouseleave' : function(){ obj.dohover(-1); }.pass([obj = this],this.links[i]),
                'click' : function() { obj.show(this.get('rel')); return false; }.pass([obj = this],this.links[i])
              });

              this.names[i].set('rel',i);
              this.names[i].removeEvents('click');
              this.names[i].addEvents({
                'mouseenter' : function(){ obj.dohover(this.get('rel')); }.pass([obj = this],this.links[i]),
                'mouseleave' : function(){ obj.dohover(-1); }.pass([obj = this],this.links[i]),
                'click' : function() { obj.show(this.get('rel')); return false; }.pass([obj = this],this.links[i])
              });
              
              if(this.contents[i].getElement('.otherctype')!=null)
              {
                this.otherctypes.push({
                  obj : this.contents[i].getElement('.otherctype').clone(1,1),
                  height : _basics.getAbsoluteScrollSize(this.contents[i].getElement('.otherctype')).y
                });
                this.contents[i].getElement('.otherctype').destroy();                
              }
              else
                this.otherctypes.push({});              
              
              if(this.boxheight < _basics.getAbsoluteScrollSize(this.contents[i]).y) this.boxheight = _basics.getAbsoluteScrollSize(this.contents[i]).y;
            }

            $('content').setStyle('height',($('content').getStyle('height').toInt() + this.boxheight)+'px');
            this.boxheight+= _basics.getAbsoluteSize(this.box).y;

            this.box.setStyles({
              'display':'block',
              'height': this.boxheight+'px',
              'overflow':'hidden'
            });
            
            return this;
          },
          
          show : function(num)
          {
            if(this.contents[num] != null && num!=this.cur_item && !this.isloading)
            {
              this.isloading = true;
              
              fadein = function(){
                // show new container
                this.contents[num].setStyles({
                  'display':'block',
                  'height':'0px',
                  'opacity':0,
                  'overflow':'hidden'
                });                  

                new Fx.Morph(this.contents[num], {
                  duration: this.duration,
                  transition : this.transition,
                  onComplete : function()
                  {
                    this.cur_item = num;
                    this.isloading = false;                      
                  }.pass([num],this)
                })
                .start({
                  'height':_basics.getAbsoluteScrollSize(this.contents[num]).y+'px',
                  'opacity':1
                });
                
                if(this.otherctypes[num].obj != null)
                {
                  this.contents[num].otherctype = this.otherctypes[num].obj.clone().setStyles({
                    'display':'block',
                    'height':'0px',
                    'opacity':0,
                    'overflow':'hidden'
                  })
                  .inject($$('#content .right')[0]);                  
  
                  new Fx.Morph(this.contents[num].otherctype, {
                    duration: this.duration,
                    transition : this.transition
                  })
                  .start({
                    'height':_basics.getAbsoluteScrollSize(this.contents[num].otherctype).y+'px',
                    'opacity':1
                  });
                }
                
              }.pass([num],this);
              
              // hide old container
              if(this.contents[this.cur_item] != null)
              {
                this.contents[this.cur_item].setStyles({
                  'overflow':'hidden',
                  'height':_basics.getAbsoluteSize(this.contents[this.cur_item]).y+'px',
                  'opacity':1
                });
                
                new Fx.Morph(this.contents[this.cur_item], {
                  duration: this.duration,
                  transition : this.transition,
                  onComplete : function()
                  {
                    this.contents[this.cur_item].setStyles({
                      'display':'none'
                    });
                  }.pass([num],this)
                })
                .start({
                  'height':0,
                  'opacity':0
                })
                .chain(fadein);

                if(this.contents[this.cur_item].otherctype != null)
                {
                  new Fx.Morph(this.contents[this.cur_item].otherctype, {
                    duration: this.duration,
                    transition : this.transition,
                    onComplete : function()
                    {
                      this.destroy();
                    }.bind(this.contents[this.cur_item].otherctype)
                  })
                  .start({
                    'height':0,
                    'opacity':0
                  });
                }

              }
              else
                fadein();
            }
          },
          
          dohover : function(num)
          {
            if(this.contents[num]==null && this.contents[this.cur_item]!=null) num = this.cur_item;
            else if(this.contents[num]==null) num = null;

            this.links.removeClass('hover'); if(num!=null) this.links[num].addClass('hover');
            this.names.removeClass('hover'); if(num!=null) this.names[num].addClass('hover');
          }
        };
      }
    }
    return null;
  },
  
  init : function()
  {
    $$('.band-members').each(function(el,i)
    {
      if((tmp = new this.view(el))) el.view = tmp.init(); delete tmp;
    }.bind(this));
  }

}


window.addEvent('domready', function(){
  _content_loader.init();
  _bandmembers.init();
});
