/* Pitch JukeBox */

/* Copyright for next block of code from http://jssoundkit.sourceforge.net/*/

/*
Copyright (c) 2006, Gustavo Ribeiro Amigo
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


    Sound.trace = function(value, isJavascript) {
        // tracing disabled
    }  

   function Player () {
      this.paused = true;
      this.stopped = true;
      this.sound = new Sound({"swfLocation" : "/jukebox-pack/SoundBridge.swf"});
      this.position = 0;
      this.frequency = 1000;
      this.isLoaded = false;
      this.duration = 0;
      this.bytesTotal = 0;
      this.playerWidth = 252;
      this.registerCallback();    
      this.container = 'jukebox';  
   }

   Player.prototype.onTimerEvent = function() {
      var isDurationOk = false;
      if(!this.paused) {
      
          var position = this.sound.getPosition();
          if(!position) position = 0;
          if(position != this.position && position != 0) {
             this.onPlaying();
          } else {
             this.onBuffering();
          }
          this.position = position;
          
          var duration = 0;
          
          // Let's trust the duration given in the playlist
          if(this.track.duration) duration = this.track.duration;
          else this.sound.getDuration();
          
          if(!duration) duration = 0;
          if(duration == this.duration && duration != 0) {
             isDurationOk = true;
             
          }
          this.duration = duration;
          var progress = position/duration;
          if(isDurationOk) {
              this.setProgressBar(progress);
          }
          
          var isBytesTotalOk = false;
          
          var bytesTotal = this.sound.getBytesTotal();
          if(bytesTotal == this.bytesTotal) {
              isBytesTotalOk = true;    
          }
          this.bytesTotal = bytesTotal;
          
          if(isBytesTotalOk) {
              var loaded =  this.sound.getBytesLoaded()/bytesTotal;
              this.setLoadedBar(loaded);
          }
          
          if (progress >= 1 && duration != 0 && position != 0) {
            this.onSoundComplete();
          }
      }
   }
   
   Player.prototype.setProgressBar = function(progress) {
        if(!progress) progress = 0;
        if ($('progress')) $('progress').style.width = progress * this.playerWidth + 'px';      
   }
   
   Player.prototype.setLoadedBar = function(loaded) {
         if(!loaded) loaded = 0;
         if($('loaded')) $('loaded').style.width = loaded * this.playerWidth + 'px';
   }   
   
   Player.prototype.onPlaying = function() {
      	if($('display')) $('display').innerHTML = "playing...";  
   }
   
   Player.prototype.onPause = function() {
      	if($('display')) $('display').innerHTML = "paused";  
   }   
   
   Player.prototype.onBuffering = function() {
      	if($('display')) $('display').innerHTML = "buffering...";  
   }   
   
   Player.prototype.registerCallback = function() {
      	setInterval(this.onTimerEvent.bind(this), this.frequency);
   }
   
   Player.prototype.onPlayButtonClick = function() {
      if(this.paused) {
         if ($('button_play')) {
	      	 $('button_play').className ='button_pause';
	         $('button_play').innerHTML = "Pause";
         }
         this.paused = false;
         if(this.stopped) {
             this.sound.loadSound(this.track.location, true);
         }
         this.sound.start(this.position/1000, 1);
         this.stopped = false;
      } else {
      	 if ($('button_play')) {
	         $('button_play').className ='button_play';
	         $('button_play').innerHTML = "Play";
      	 }
         this.position = this.sound.getPosition();
         this.sound.stop();         
         this.paused = true;
         this.onPause();
      }
   }

   Player.prototype.onForwardButtonClick = function() {
         this.position = 0;
         this.duration = 0;
         this.sound.start(this.duration/1000, 1);
         this.sound.stop();
         this.currentTrack++;
         if(this.currentTrack >= this.playlist.length) this.currentTrack = 0;
         this.loadTrack(this.playlist[this.currentTrack]);
         this.stopped = true;
         this.setProgressBar(0);
         this.setLoadedBar(0);
         if(!this.paused) {
            if ($('display')) $('display').innerHTML = "";
            this.paused = true;
            this.onPlayButtonClick();
         }
   }   

   Player.prototype.onBackButtonClick = function() {
         this.position = 0;
         this.duration = 0;
         this.sound.start(this.duration/1000, 1);
         this.sound.stop();
         this.currentTrack--;
         if(this.currentTrack < 0 ) this.currentTrack = this.playlist.length - 1;
         this.loadTrack(this.playlist[this.currentTrack]);
         this.stopped = true;
         this.setProgressBar(0);
         this.setLoadedBar(0);
         if(!this.paused) {
            if ($('display')) $('display').innerHTML = "";
            this.paused = true;
            this.onPlayButtonClick();
         }
   }      

   Player.prototype.onStopButtonClick = function() {
       this.paused = true;
       this.stopped = true;
       this.position = 0;
       this.duration = 0;
       this.sound.start(this.duration/1000, 1);
       this.sound.stop();         
       this.setProgressBar(0);
       if ($('button_play')) $('button_play').className ='button_play';
       if ($('display')) $('display').innerHTML = "stopped";  
       if ($('button_play')) $('button_play').innerHTML = "Play";
   }   
   
   Player.prototype.watch = function (variable, line){
      $('debug').innerHTML += line + " : variable " + variable + " = " + eval(variable) + "<br />"; 
   }
   
   Player.prototype.loadTrack = function(track) {
      //this.watch("this.currentTrack",304);
      this.track = track;
      var info ="";
      if(track.creator)  info += "<b>Artist:</b> " + track.creator + "<br />";
      if(track.album) info += "<b>Album:</b> " + track.album + "<br />";
      if(track.title) info += "<b>Song:</b> " + track.title + "<br />";
      if(track.location) info += "<a href='" + unescape(track.location) + "' target='_blank'> download </a>";
      if(track.location && track.info) info += "/";
      if(track.info) info += "<a href='" + unescape(track.info) + "' target='_blank'> info </a>";
      if(track.info && track.license) info += "/";
      if(track.license) info += "<a href='" + unescape(track.license) + "' target='_blank'> license </a>";
      $('track_info').innerHTML = info;
      if(track.image) $('album_image').innerHTML = "<img src='"+track.image+"' alt='"+ track.album + "' width='48' height='48' />" ;
      else $('album_image').innerHTML = "";
   }
   
   Player.prototype.loadPlaylist = function(playlist) {
      this.playlist = playlist;
      this.currentTrack = 0;
      this.loadTrack(this.playlist[0]);
   }
   
   Player.prototype.onSoundComplete = function() {
      if(!this.paused) {
        this.onForwardButtonClick();
      }
   }
   
/* End of jssoundkit code */

/* Extensions */

	/* To start the player when any configured link on the page is clicked */

	Player.prototype.playTrack = function(id) {
		this.paused = true;
        this.stopped = true;
        this.position = 0;
        this.duration = 0;
        this.sound.start(this.duration/1000, 1);
        this.sound.stop();         
        this.setProgressBar(0);
        this.loadTrack(this.playlist[id]);
        this.onPlayButtonClick();
	}
	
	/* Writes the jukebox to the container */
	
	Player.prototype.writeToPage = function() {
		this.createBtn('button_back', 'Back');
		this.createBtn('button_stop', 'Stop');
		this.createBtn('button_play', 'Play');
		this.createBtn('button_forward', 'Forward');
		this.addListeners();
	}
	
	/* Creates Button in DOM */
	
	Player.prototype.createBtn = function(id, text) {
		var button  = new Element('button', { id:id,'class': id }).update(text);
		$(this.container).insert(button);
		
	}
	
	/* Adds Event listeners to the buttons */
	
	Player.prototype.addListeners = function() {
		
		/* Should add dynamically when the btn is created in writeToPage() */
		Event.observe('button_back', 'click', function() {
			player.onBackButtonClick();
		});
		
		Event.observe('button_stop', 'click', function() {
			player.onStopButtonClick();
		});
		Event.observe('button_play', 'click', function() {
			player.onPlayButtonClick();
		});
		Event.observe('button_forward', 'click', function() {
			player.onForwardButtonClick();
		});
	}
	
	/* Plays Track from just Url */
	
	Player.prototype.playUrl = function(url) {
		var t = new Array();
		t["location"] = url;
		this.track = t;
		this.onPlayButtonClick();
		
		
	}
/* End of Extensions */



/* Initiate */

var player;

