/*
 *
 * JScript for pages containing songs
 */

var PlayList = new Class({
  initialize: function() {
    this.name = document.getElement('div.listname').innerHTML;
    this.songids = [];
    this.songs = {};
    this.songByPlayer = {};
    this.playing = false;

    this.addSongs();
    this.done = false;
    this.playerid = 'myplayer12398989';
    
    this.swf = new SWFObject('../../lib/player.swf',this.playerid,'0','0','8');
    this.swf.addParam('allowscriptaccess','always');
    this.swf.addVariable('type','mp3');
    this.swf.addVariable('width','0');
    this.swf.addVariable('height','0');
    this.swf.addVariable('javascriptid', this.playerid);
    this.swf.addVariable('enablejs','true');
    this.swf.write('embedPlayer');
    
    this.player = (navigator.appName.indexOf("Microsoft") != -1)?
      window[this.playerid] : document[this.playerid];

    getUpdate = function(typ, pr1, pr2, swf) {
      /* called by flash all the time */
      if (this.playing) {
        this.playing.getUpdate(typ, pr1, pr2);
      }
    }.bind(this);
    
    document.addEvent('keydown', function(event) {
      var event = new Event(event);
			if (event.key == 'enter') this.toggle();
			if (event.key == 'left') this.playPrev();
			if (event.key == 'right') this.playNext();
		}.bind(this));
    
    
    $('playlist').setStyle('visibility', 'visible');
    
    window.addEventListener('resize', function() {
      this.adjustPositions();
    }.bind(this), false);
  },
  addSong: function(song) {
    this.songids.push(song.id);
    this.songs[song.id] = song;
    this.songByPlayer[song.playerid] = song;
  }, 
  addSongs: function() {
    var esongs = document.getElements('div.song');
    for (i = 0; i < esongs.length; ++i) {
      var song = new Song(esongs[i], this);
      this.addSong(song);
    }
  },
  stopAllBut: function(songid) {
    for (i = 0; i < this.songids.length; ++i) {
      var song = this.songs[this.songids[i]];
      if (songid != song.id) song.stopped();
    }
  },
  play: function(song) {
    this.playing = song;
    this.player.loadFile({file: song.file});
    this.player.sendEvent('playpause');
    document.title = this.name + ': ' + song.name;
  },
  pause: function(song) {
    if (this.playing) {
      this.player.sendEvent('playpause');
    }
  },
  toggle: function() {
    this.playing? this.playing.togglePlay() : this.playNext();
  },
  stop: function() {
    if (this.playing) {
      this.playing = false;
      this.player.sendEvent('stop');
      document.title = this.name;
    }
  },
  playNext: function() { 
    var nid = this.getNext(this.playing.id);
    this.stop();
    this.songs[nid].play();
    this.scrollToPlaying();
  },
  playPrev: function() { 
    var nid = this.getPrev(this.playing.id);
    this.songs[nid].play();
    this.scrollToPlaying();
  },
  adjustPositions: function(songid) {
    for (i = 0; i < this.songids.length; ++i) {
      this.songs[this.songids[i]].adjustPosition();
    }
  },
  getNext: function(id) {
    var i = this.songids.indexOf(id);
    var next = (i < (this.songids.length - 1))? i+1 : 0;
    return this.songids[next];
  },
  getPrev: function(id) {
    var i = this.songids.indexOf(id);
    var prev = (i > 0)? i-1 : (this.songids.length-1);
    return this.songids[prev]; 
  },
  scrollToPlaying: function() {
    var win_y_offset = window.getScroll().y;
    var pco = this.playing.element.getCoordinates();
    var rtop = pco.top - win_y_offset;
    var rbottom = window.getSize().y - (pco.bottom - win_y_offset);
    if (rtop < 50 || rbottom < 10) {
	var scroll_y = (window.getSize().y - pco.height) / 2;
	var scroll = new Fx.Scroll(window, {
            offset: { 'x': 0, 'y': -scroll_y }
        });
    	scroll.toElement(this.playing.element);
    }
  }
});

var Song = new Class({
  initialize: function(e, playlist) {
    this.element = $(e);
    this.id = $(e).id;
    this.playerid = 'player'+this.id;
    this.playlist = playlist;
    this.playing = false;
    this.file = $(e).getElement('div.songhref').innerHTML;
    this.name = $(e).getElement('div.songname').innerHTML;
    this.timer = $(e).getElement('div.songtimer');
    if (!this.file) this.file = escape(this.id)+'.mp3';
    
    this.element.addEvent('click', function(e) {
      var ev = new Event(e);
      if ($(ev.target).get('tag') != 'a') {
      	this.togglePlay();
	return false;
      }
      return true;
    }.bind(this));
  },
  play: function() {
    if (!this.playing) {
      this.playlist.stopAllBut(this.id);
      this.element.addClass('playing');
      this.timer.setStyle('visibility', 'visible');
      this.adjustPosition();
      this.playing = true;
      this.paused = false;
      this.playlist.play(this);
    }
  },
  pause: function() {
    if (this.playing) {
      this.playlist.pause();
      this.paused = true;
    }
  },
  stopped: function() {
    if (this.playing) {
      this.timer.setStyle('visibility', 'hidden');
      this.timer.set('html', '');
      this.element.removeClass('playing');
      this.playing = false;
      this.paused = false;
    }
  },
  adjustPosition: function() {
    /* all these changes will take effect when the jscript returns to the browser, not before 
     * we use visibility: hidden instead of display:none, since not displayed elements seem
     * to have no dimendions.
     */
    var coord = this.element.getCoordinates();
    var tco = this.timer.getCoordinates();
    var voffset = (tco.height - coord.height) / 2;
    this.timer.setStyle('z-index', 10);
    this.timer.setStyle('position', 'absolute');
    this.timer.setStyle('top', coord.top - voffset);
    this.timer.setStyle('left', coord.left + coord.width - 200);
  },
  togglePlay: function() {
    this.playing? this.pause() : this.play();
  },
  getUpdate: function(type, pr1, pr2) {
		switch(type) {
			case 'time':
				var string = '';
				if (!(pr1 < 1 && !this.playing)) {
					var sec = pr1 % 60;
					var min = (pr1 - sec) / 60;
					var min_formatted = min ? min+':' : '';
					var sec_formatted = min ? (sec < 10 ? '0'+sec : sec) : sec;
					string = min_formatted + sec_formatted;
				}
				this.timer.set('html', string);
				this.adjustPosition();
        			break;
			case 'state':
 				if (pr1 == 2) {
					this.timer.removeClass('grey');
					this.timer.addClass('green');
				} 
        			else {
					this.timer.removeClass('green');
					this.timer.addClass('grey');
				}
				if (pr1 == 3) {
          				this.playlist.playNext.delay(5, this.playlist);
				}
        			break;
			case 'load':
          			break;
		}    
  }
});

window.addEvent('domready', function(){
	var Play = new PlayList();

	var aimg = document.getElement('.albumimg img');
	aimg.set('morph', {duration: 500});
	aimg.addEvents({
		mouseenter: function(){
			aimg.morph({
				width: '333px',
			});
		},
		mouseleave: function(){
			aimg.morph({
				width: '60px',
			});
		}
	});

	var els = document.getElements('.songimg img');
        for (var i = 0; i < els.length; ++i) {
		var el = els[i];
		el.addEvents({
			mouseenter: function(){
				aimg.src = this.src;
				aimg.morph({
					width: '333px',
					opacity: 1.0
				});
			},
			mouseleave: function(){
				aimg.morph({
					width: '60px',
					opacity: 0.0
				});
			}
		});
	}
})





