_niftyPlayer = {
  niftyplayerCheck : false,
  niftyPlayerTracks : new Array(),
  niftyPlayerId : 'niftyplayer',
  currentTrack : 0,
  
  currentSingleTrack : null,
  
  swfobj : false,

  initObj : function() {
    if(!$chk(this.obj))
    {
      this.obj = this.FlashHelper.getMovie(this.niftyPlayerId+(!this.swfobj ? '_flash' : ''));
      // if(typeof(this.obj.SetVariable)=='undefined') this.obj = this.obj.getElement('embed');
      
      this.registerEvent('onPlay', '_niftyPlayer.checkNiftyPlayer()');
    }
    if(!this.FlashHelper.movieIsLoaded(this.obj)) return false;
    else return true;
  },
  
  init : function(options){

    classname = !$chk(options.trackclass) ? 'niftyplayer' : options.trackclass
    this.insertPlayerInto = $$('body')[0];

    if($chk(options.insertinto))
      if($type(options.insertinto) == 'string' && $chk($(options.insertinto)))
        this.insertPlayerInto = $(options.insertinto);
      else
        this.insertPlayerInto = options.insertinto;
    
    if($chk(this.niftyPlayerTracks = $$('.'+classname)))
    {
      this.niftyPlayerTracks.each(function(track,index){
        track.addEvent('click',function(){
          if(!this.initObj()) return false;
          
          if($chk(_niftyPlayer.currentSingleTrack))
          {
            _niftyPlayer.stop();
            _niftyPlayer.currentSingleTrack.removeClass('playing');
            _niftyPlayer.currentSingleTrack = null;
          }
          
          switch(_niftyPlayer.getState())
          {
            case 'empty' :
            case 'stopped' :
              this.loadAndPlay(track.get('href'));
              this.currentTrack = index;
            break;
            case 'paused' :
              if(this.currentTrack==index)
                this.play();
              else
              {
                this.stop();
                this.currentTrack = index;
                this.loadAndPlay(track.get('href'));
              }
            break;
            case 'playing' :
              if(this.currentTrack==index)
                this.pause();
              else
              {
                this.stop();
                this.currentTrack = index;
                this.loadAndPlay(track.get('href'));
              }
            break;
          }
          this.updateClasses();

          return false;
        }.bind(this));
      }.bind(this));
    
      nifty_audioplayer = new Element('div',{
        'id':'audio-player'
      })
      .inject(this.insertPlayerInto);
        
      if(this.niftyPlayerTracks.length>0)
      {
        this.button_playpause = new Element('a', {
          'href' : 'javascript:void(0)',
          'class' : 'play'
        })
        .set('html','&gt;')
        .addEvent('click',function(){
          if(!_niftyPlayer.initObj()) return false;

          if($chk(_niftyPlayer.currentSingleTrack))
          {
            _niftyPlayer.stop();
            _niftyPlayer.currentSingleTrack.removeClass('playing');
            _niftyPlayer.currentSingleTrack = null;
          }

          switch(_niftyPlayer.getState())
          {
            case 'empty' :
            case 'stopped' :
              if(text = _niftyPlayer.niftyPlayerTracks[_niftyPlayer.currentTrack].get('title')) _niftyPlayer.updateDisplay(text);
              _niftyPlayer.niftyPlayerTracks[_niftyPlayer.currentTrack].fireEvent('click');
            break;
            case 'paused' :
              if(text = _niftyPlayer.niftyPlayerTracks[_niftyPlayer.currentTrack].get('title')) _niftyPlayer.updateDisplay(text);
              _niftyPlayer.updateClasses('play');
              _niftyPlayer.play();
            break;
            case 'playing' :
              _niftyPlayer.updateDisplay('');
              _niftyPlayer.updateClasses('pause');
              _niftyPlayer.pause();
            break;
          }
          
          _niftyPlayer.updatePlayButton();
          
          
        })
        .inject(nifty_audioplayer);
        
        this.button_prev = new Element('a', {
          'href' : 'javascript:void(0)',
          'class' : 'prev'
        })
        .addEvent('click',function(){
          if(!_niftyPlayer.initObj()) return false;
          if(_niftyPlayer.getState()=='playing' && !$chk(_niftyPlayer.currentSingleTrack)) _niftyPlayer.playPrev();
          _niftyPlayer.updatePlayButton();
        })
        .set('html','&#0171;')
        .inject(nifty_audioplayer);

        this.button_next = new Element('a', {
          'href' : 'javascript:void(0)',
          'class' : 'next'
        })
        .addEvent('click',function(){
          if(!_niftyPlayer.initObj()) return false;
          if(_niftyPlayer.getState()=='playing' && !$chk(_niftyPlayer.currentSingleTrack)) _niftyPlayer.playNext();
          _niftyPlayer.updatePlayButton();
        })
        .set('html','&#0187;')
        .inject(nifty_audioplayer);
        
        this.display = new Element('div', {
          'id' : 'niftyPlayerDisplay'
        })
        .set('html','')
        .inject(nifty_audioplayer);
      }

      new Element('div',{'id':'niftyplayer'}).inject(nifty_audioplayer);
    
      if(this.swfobj)
      {
        swfobject.embedSWF(
          TEMPLATE_DIR+"/../addons/admintools/js/niftyplayer/niftyplayer.swf",
          this.niftyPlayerId,
          "100%", "40", "8",
          "./flash/playerProductInstall.swf",
          {as:0},
          {quality:"high",wmode:"transparent",scale:"exactfit",salign:"tm",menu:"false"},
          false);
      }
      else
      {
        new Swiff(TEMPLATE_DIR+'/../addons/admintools/js/niftyplayer/niftyplayer.swf',{
          id:this.niftyPlayerId+'_flash',
          width:160,height:40,
          container:$(this.niftyPlayerId),
          params:{wmode:'transparent',allowScriptAccess:true,quality:'high',allowFullScreen:false},
          vars:{as:0},properties:{tmp:'0'}});
      }
    }
  },
  
  updatePlayButton : function()
  {
    if(_niftyPlayer.getState()!='loading')
    {
      _niftyPlayer.button_playpause.removeClass('loading').setStyle('opacity',1);
      _niftyPlayer.button_prev.setStyle('opacity',1);
      _niftyPlayer.button_next.setStyle('opacity',1);
    }
    else {
      _niftyPlayer.button_playpause.addClass('loading').setStyle('opacity',.5);
      _niftyPlayer.button_prev.setStyle('opacity',0);
      _niftyPlayer.button_next.setStyle('opacity',0);
      _niftyPlayer.updatePlayButton.delay(10);
    }    
  },
  
  updateDisplay : function(text)
  {
    if(typeof(text)=='string' && typeof(this.display)=='object')
    {
      this.display.set('html',text);
      this.scrollDisplay(true);
    }
  },
  
  scrollDisplay : function(reset)
  {
    if(typeof(this.display)=='object')
    {
      if(reset)
      {
        this.display.setStyle('text-indent',0);
        if(this.display.effect) this.display.effect.cancel();
        if(this.display.interval) $clear(this.display.interval);
        this.display.interval = (function(){ this.scrollDisplay(); }.bind(this)).delay(1000);
        return false; 
      }
      
      if(this.display.getScrollSize().x > this.display.getSize().x || this.display.getStyle('text-indent').toInt()<0)
      {
        this.display.moveFaktor = this.display.getScrollSize().x / this.display.getSize().x;
        this.display.effect = new Fx.Morph(this.display,{
          duration : 2000 * this.display.moveFaktor,
          transition : Fx.Transition.Linear,
          onComplete : function()
          {
            this.display.interval = (function(){ this.scrollDisplay(); }.bind(this)).delay(1000);
          }.bind(this)
        })
        .start({
          'text-indent':(this.display.getStyle('text-indent').toInt()>=0 ? this.display.getSize().x-this.display.getScrollSize().x : 0)
        });
      }
      else
      {
        this.display.setStyle('text-indent',0);
        if(this.display.effect) this.display.effect.cancel();
        if(this.display.interval) $clear(this.display.interval);
      }
    }
  },
  
  
  updateClasses : function()
  {
    this.niftyPlayerTracks.removeClass('playing');
    this.niftyPlayerTracks.removeClass('paused');
    if(_niftyPlayer.getState()=='playing' || _niftyPlayer.getState()=='stopped') {
      this.niftyPlayerTracks[this.currentTrack].addClass('playing');
      this.button_playpause.removeClass('pause');
      this.button_playpause.addClass('play');
    }
    else
    {
      this.niftyPlayerTracks[this.currentTrack].addClass('paused');
      this.button_playpause.removeClass('play');
      this.button_playpause.addClass('pause');
    }
  },
  
  FlashHelper : {
  	movieIsLoaded : function (theMovie)
  	{
  	 return true;
  		if (typeof(theMovie) != "undefined") return theMovie.PercentLoaded() == 100;
  		else return
  		false;
    },
  
  	getMovie : function (movieName)
  	{
    	if (navigator.appName.indexOf ("Microsoft") !=-1) return window[movieName];
  	  else return document[movieName];
  	}
  },
  
  
  play : function () {
		this.obj.TCallLabel('/','play');
	},
  
  stop : function () {
		this.obj.TCallLabel('/','stop');
	},
  
  pause : function () {
		this.obj.TCallLabel('/','pause');
	},
  
  playToggle : function () {
		this.obj.TCallLabel('/','playToggle');
	},
    
  reset : function () {
		this.obj.TCallLabel('/','reset');
	},
    
  load : function (url) {
    
		this.obj.SetVariable('currentSong', url);
		this.obj.TCallLabel('/','load');
	},
  
  loadAndPlay : function (url) {
		this.load(url);
		
		this.play();
	},
  
  getState : function () {
		var ps = this.obj.GetVariable('playingState');
		var ls = this.obj.GetVariable('loadingState');

		// returns
		//   'empty' if no file is loaded
		//   'loading' if file is loading
		//   'playing' if user has pressed play AND file has loaded
		//   'stopped' if not empty and file is stopped
		//   'paused' if file is paused
		//   'finished' if file has finished playing
		//   'error' if an error occurred
		if (ps == 'playing')
			if (ls == 'loaded') return ps;
			else return ls;

		if (ps == 'stopped')
			if (ls == 'empty') return ls;
			if (ls == 'error') return ls;
			else return ps;

		return ps;

	},
  
  getPlayingState : function () {
		// returns 'playing', 'paused', 'stopped' or 'finished'
		return this.obj.GetVariable('playingState');
	},
  
  getLoadingState : function () {
		// returns 'empty', 'loading', 'loaded' or 'error'
		return this.obj.GetVariable('loadingState');
	},
    
  registerEvent : function (eventName, action) {
		// eventName is a string with one of the following values: onPlay, onStop, onPause, onError, onSongOver, onBufferingComplete, onBufferingStarted
		// action is a string with the javascript code to run.
		//
		// example: niftyplayer('niftyPlayer1').registerEvent('onPlay', 'alert("playing!")');

		this.obj.SetVariable(eventName, action);
	},
	
	playNext : function()
	{
    next = this.currentTrack >= this.niftyPlayerTracks.length-1 ? 0 : this.currentTrack+1;
    if(text = this.niftyPlayerTracks[next].get('title')) this.updateDisplay(text);
    this.niftyPlayerTracks[next].fireEvent('click');
  },
  
	playPrev : function()
	{
    next = this.currentTrack == 0 ? this.niftyPlayerTracks.length-1 : this.currentTrack-1;
    if(text = this.niftyPlayerTracks[next].get('title')) this.updateDisplay(text);
    this.niftyPlayerTracks[next].fireEvent('click');
  },
  
  checkNiftyPlayer : function(){
    if($chk(this.niftyPlayerTracks))
    {
      this.niftyplayerCheck = (function(){this.checkNiftyPlayer();}.bind(this)).delay(1000,this);
      
      if(this.getState()=='playing')
      {
        this.niftyPlayerTracks.each(function(el,i){
          el.set('html',el.get('html').split(' | ')[0]);
          if(el.hasClass('playing'))
          {
            el.set('html',el.get('html')+' | playing');

          }
        });
      }
        
      if(this.getState()=='finished')
      {
        $clear(this.niftyplayerCheck);
        if(!this.currentSingleTrack)
        {
          this.playNext();
        }
        else
          this.currentSingleTrack.removeClass('playing');
      }
    }
  },
  
  playSingleFile : function(link)
  {
    if($chk(link) && $chk(link.get('href')))
    {
      if(!this.initObj()) return false;
      loadnew = true;
      
      // stop old track
      if($chk(this.currentSingleTrack))
      {
        if(this.currentSingleTrack == link && this.getState()=='paused')
        {
          this.play()
          this.currentSingleTrack.addClass('playing');
          loadnew = false;
        }
        else
        {
          this.stop();
          this.currentSingleTrack.removeClass('playing');
        }
      }
      
      if(loadnew)
      {
        // turn off the player
        switch(this.getState())
        {
          case 'paused' :
          case 'playing' :
            this.stop();
            this.updateClasses();
          break;
        }
        
        // play the item
        this.currentSingleTrack = link;
        this.currentSingleTrack.addClass('playing');
        this.loadAndPlay(link.get('href'));
      }
    }
  },
  
  addSingleTrackPlayer : function(box)
  {
    if($chk(box) && $chk(tracks = box.getElements('.niftyplayer-singletrack')))
    {
      tracks.each(function(el){
        
        el.addEvent('click',function(){
          if(this.hasClass('playing'))
          {
            _niftyPlayer.pause();
            _niftyPlayer.currentSingleTrack.removeClass('playing');
            // _niftyPlayer.currentSingleTrack = null;
          }
          else
            _niftyPlayer.playSingleFile(el);

          _niftyPlayer.updateDisplay('');
          
          return false;
        })
        
//        alert(this.currentSingleTrack.get('href'));

        if($chk(_niftyPlayer.currentSingleTrack) && _niftyPlayer.currentSingleTrack.get('href') == el.get('href') && this.getState()=='playing')
        {
          el.addClass('playing');
          _niftyPlayer.currentSingleTrack = el;
        }
      });
    }
  }
}

var youtube_handlePlayerStateChange = function (state)
{
  switch (state) {
    case 1:
    case 3:
      // Video has begun playing/buffering
      videoContainer.cycle('pause');
      break;
    case 2:
    case 0:
      // Video has been paused/ended
      videoContainer.cycle('resume');
      break;
  }
};
  
var youtube_onYouTubePlayerReady = function(player)
{
  if($chk(player))
  {
    if (player.addEventListener) {
      player.addEventListener('onStateChange', 'youtube_handlePlayerStateChange', false);
    }
    else {
      player.attachEvent('onStateChange', 'youtube_handlePlayerStateChange', false);
    }
  }
}



window.addEvent('domready',function(){
  _niftyPlayer.init({
    'trackclass':'niftyplayer',
    'insertinto':$('audioplayer')
  });
  _niftyPlayer.addSingleTrackPlayer($$('body')[0]);
  
});

      
      



