function debug2( s ){
  alert( s );
}

var Player = new Class({
  initialize: function(){
    this.attempted = false;
    this.started = false;
    this.title = null;
    this.url = null;
    this.state = 0;
    this.STOP = 1;
    this.PAUSE = 2;
    this.PLAY = 3;
    this.lc = generateLine();

    this.videoplayer = null;
    this.resize_interval = -1;
    this.showlargevideo_interval = -1;
    this.windowstate = 0;
    this.SMALL = 1;
    this.LARGE = 2;

    this.scrollfx1 = null;
    this.scrollfx2 = null;

    this.mainsongtitle = $('track_info');
    this.mainsongaction = $('track_actions');
    this.volume      = $('volume');
    this.barcontainer= $('barcontainer');
    this.playbutton  = $('playbutton');
    this.stopbutton  = $('stopbutton');
    this.pausebutton = $('pausebutton');
    this.prevbutton  = $('prevbutton');
    this.nextbutton  = $('nextbutton');
    this.bufferbar   = $('bufferbar');
    this.progressbar = $('progressbar');
    this.sliderbutton = $('sliderbutton');
    this.timebar = $('timebar');
    this.seekbar = $('seekbar');

    this.buffercomplete = false;
    this.songid = null;
    this.playlistnumber = null;
    this.playlist = null;
    this.track    = false;

    this.prevbutton.addEvent('click', function(_player){
      _player.prevSong(); }.pass(this) );
    this.nextbutton.addEvent('click', function(_player){
      _player.nextSong(); }.pass(this) );

    this.volume.addEvent('click', this.handlevolumeclick.bindWithEvent(  this.volume, this ) );

    this.playbutton.addEvent('click', function(_player){
      _player.startSong(); }.pass(this) );
    this.pausebutton.addEvent('click', function(_player){
      _player.pauseSong(); }.pass(this) );
    this.stopbutton.addEvent('click', function(_player){
      _player.stopSong(); }.pass(this) );
    function handlerseek( event, _player ){
      var x = event.page.x;
      var left = _player.bufferbar.getCoordinates().left;
      var right = left + _player.bufferbar.getCoordinates().width;
      if( left <= x && x <= right ){
        var perc  = _player.bufferbar.getStyle('width');
        var index = perc.indexOf('%');
        if( index != -1 ) perc = parseInt( perc.substring(0,index) );
        var width = _player.bufferbar.getCoordinates().width / (perc/100);
        var delta = (event.page.x-_player.bufferbar.getCoordinates().left);
        var seek = parseInt( (delta / width) * 100 );
        _player.seek( seek );
      }
    }
    this.seekbar.addEvent('click', handlerseek.bindWithEvent( this.seekbar , this ) );

    this.initflash();
  },
  markDead: function(){
    if( this.track == false ) return;
    if( this.url == null ) return;
    if( this.playlist == null ) return;
    for( var a = 0; a < this.playlist.length; a++ ){
      if( this.playlist[a].url == this.url ) this.playlist[a].isDead = true;
    }
  },
  checkAllDead: function(){
    if( this.track == false ) return false;
    if( this.url == null ) return false;
    if( this.playlist == null ) return false;
 
    var alive = false;
    for( var a = 0; a < this.playlist.length; a++ ){
      if( typeof(this.playlist[a].isDead) == 'undefined' || this.playlist[a].isDead == null || this.playlist[a].isDead == false ){
        alive = true; break;
      }
    }
    if( alive ) return false;
    else return true;
  },
  switchlargeview : function(){
    clearTimeout( this.showlargevideo_interval );
    this.showlargevideo_interval = setTimeout( "PLAYER._switchlargeview()", 2000 );
  },
  _switchlargeview : function(){   
    this.windowstate = this.LARGE;
    $('video').setStyle('position', 'absolute');
    $('video').setStyle('left', '8px');
    $('video').setStyle('top', '78px');
    $('video').setStyle('width', '400px');
    $('video').setStyle('height', '280px');

    $('videoswf').width  = 400;
    $('videoswf').height = 280; 
    if( this.resize_interval == -1 ){
      this.resize_interval = setInterval( "PLAYER.resizeVideo()", 1000 );
    }
  },
  switchsmallview : function(){
    this.windowstate = this.SMALL;
    if( this.largeviewfinal_interval != -1 ) clearInterval( this.largeviewfinal_interval );
    $('video').setStyle('position', 'absolute');
    $('video').setStyle('left', '432px');
    $('video').setStyle('top', '45px');
    $('video').setStyle('width', '145px');
    $('video').setStyle('height', '105px');
    $('videoswf').width = 145;
    $('videoswf').height = 105;
    if( this.resize_interval == -1 ){
      this.resize_interval = setInterval( "PLAYER.resizeVideo()", 1000 );
    }
  },
  resizeVideo: function(){
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    this.videoplayer = (isIE) ? window["videoswf"] : document["videoswf"];
    if( typeof(this.videoplayer) != "undefined" && typeof(this.videoplayer.resizeVideo) != "undefined" ){
      this.videoplayer.resizeVideo();
    }
  },
  initflash : function(){   
    if( this.started == true ) return;
    if( this.attempted == false ){
       this.attempted = true;
       
       var flashvars = {};
       var params = { wmode: "transparent", allowScriptAccess: "always", quality: "high" };
       var attributes = { id: "audioplayer", name: "audioplayer" };
       // /swf/MediaConsoleController.swf
       swfobject.embedSWF( statichost + '/swf/Controller.swf?lc=' + this.lc, "playercode", 1, 1, "8.0.0", null, flashvars, params, attributes);
      
       flashvars = {};
       params = { wmode: "transparent", allowScriptAccess: "always", quality: "high" };
       attributes = { id: "videoswf", name: "videoswf" };
       // /swf/MediaConsoleViewer.swf?
       swfobject.embedSWF( statichost + '/swf/Viewer.swf?lc=' + this.lc, "videoswf", 145, 105, "8.0.0", null, flashvars, params, attributes );

       $('video').setStyle('position', 'absolute');      
       $('video').setStyle('z-index', 10 );
//       $('videoswf').style.zIndex = 10;
    }

    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    this.musicplayer = (isIE) ? window["audioplayer"] : document["audioplayer"];   
    if( typeof(this.musicplayer) != "undefined" && typeof(this.musicplayer.playSong) != "undefined" ) this.started = true;
    else return;
  },
  handlevolumeclick: function( event, _player ){
    var x = event.page.x;
    var target = event.target;
    var left   = $(target).getCoordinates().left;
    var width  = $(target).getCoordinates().width;
    var perc   = parseInt(100*(x-left)/width);
    if( perc < 12.5 ) target.src = statichost + "/images/mediaconsole/volume_1.png";
    else if( perc >= 12.5 && perc < 25 ) target.src = statichost + "/images/mediaconsole/volume_2.png";
    else if( perc >= 25 && perc < 37.5 ) target.src = statichost + "/images/mediaconsole/volume_3.png";
    else if( perc >= 37.5 && perc < 50 ) target.src = statichost + "/images/mediaconsole/volume_4.png";
    else if( perc >= 50 && perc < 62.5 ) target.src = statichost + "/images/mediaconsole/volume_5.png";
    else if( perc >= 62.5 && perc < 75 ) target.src = statichost + "/images/mediaconsole/volume_6.png";
    else if( perc >= 75 && perc < 87.5 ) target.src = statichost + "/images/mediaconsole/volume_7.png";
    else if( perc >= 87.5 ) target.src = statichost + "/images/mediaconsole/volume_8.png";
    _player.setVolume( perc );
  },
  playView : function(){
    this.playbutton.setStyle('display', 'none');
    if( browser.isIE  ){
      this.pausebutton.setStyle('display', 'block');
      this.pausebutton.setStyle('float', 'left');
    }else{
      this.pausebutton.setStyle('display', 'table-cell');
    }
  },
  pauseView : function(){
    if( browser.isIE  ){
      this.playbutton.setStyle('display', 'block');
      this.playbutton.setStyle('float', 'left');
    }else{
      this.playbutton.setStyle('display', 'table-cell');
    }
    this.pausebutton.setStyle('display', 'none');
  },
  showTitle: function(){

    var html = '&nbsp;&nbsp;&nbsp;&nbsp; ';
    if( this.url != null ){
      var furl = fix4param( this.url );
      var infoclick = "infoSong('"+ furl+"' );return false";
      html += '<a href="#" onclick="'+infoclick+'">Info</a> ';
      if( this.track == false ){
        var ftitle = fix4param( this.title );
        var furl   = fix4param( this.url );
        var addsongclick = "addSong('"+ furl +"', '"+ ftitle + "');return false";
        html += '| <a href="#" onclick="'+addsongclick+'">Add</a> ';
      }
    }    
    if( this.track == true ){
      var furl = fix4param( this.url );
      var ftitle = fix4param( this.title );
      var modifyclick = "showmodifysong('"+ ftitle+"', '"+ furl+"', '"+ this.songid +"', '"+ this.playlistnumber +"' );return false";
      var deleteclick = "deleteSong( '"+ this.playlistnumber +"', '"+ this.songid +"' );return false";
      html += ' | <a href="#" onclick="'+modifyclick+'">Modify</a> ' + 
              ' | <a href="#" onclick="'+deleteclick+'">Delete</a> ';
    }

    clearStatusDiv();

    this.mainsongtitle.innerHTML = this.title;
    this.mainsongaction.innerHTML = html;
  },
  playSong: function( title, url, track, playlist, playlistnumber, id ){
    this.initflash();
    if( ! this.started ){
      dialogAlertTimeout('Sorry the Player is still loading. Try Again', 1000 );
      return;
    }

    this.buffercomplete = false;
    if( track != null ) this.track = track;
    else this.track = false;
    this.playlist = playlist;
    this.playlistnumber = playlistnumber;
    this.songid = id;
    this.title = decodeURIComponent( title );
    this.url = decodeURIComponent( url );
    this.state = this.PLAY;
    this.showTitle();
    this.playView();
    this.setbufferbar( 0 );
    this.setprogressbar( 0 );
    this.settime( 0, 0 );
    this.musicplayer.loadSong( this.title, this.url );
  },
  songStarted: function(){
    var ajax = new Ajax( null, null );
    var uri = "/media/mediaplay!ajax.action?url="+ encodeURIComponent( this.url ) +"&" +generateLine() + "=0";
    ajax.get( uri, null, false );
  },
  prevSong: function(){
    if( this.track == false ) return;
    if( this.url == null ) return;
    if( this.playlist == null ) return;
    var a = 0;
    if( this.playlist.length == 1 ){
      this.playSong( this.title, this.url, true, this.playlist, this.playlistnumber, this.songid );
    }else{
      for( ; a < this.playlist.length; a++ ){
        if( this.playlist[a].url == this.url && this.playlist[a].title == this.title ){ break; }
      }
      a--;
      if( a < 0 ) a = a + this.playlist.length;
      var song = this.playlist[(a%this.playlist.length)];
      this.playSong( song.title, song.url, true, this.playlist, this.playlistnumber, this.songid );
    }
  },
  nextSong: function(){
    if( this.track == false ) return;
    if( this.url == null ) return;
    if( this.playlist == null ) return;
    if( this.checkAllDead() == true ){
      alert('All the songs in this playlist are no longer working. Please update your playlist');
      return;
    }

    var a = 0;
    if( this.playlist.length == 1 ){
      this.playSong( this.title, this.url, true, this.playlist, this.playlistnumber, this.songid );
    }else{
      for( ; a < this.playlist.length; a++ ){
        if( this.playlist[a].url == this.url && this.playlist[a].title == this.title ){ break; }
      }
      var song = this.playlist[(a+1)%this.playlist.length];
      this.playSong( song.title, song.url, true, this.playlist, this.playlistnumber, this.songid );
    }
  },
  startSong: function(){
    if( this.state == this.PAUSE ){
      this.resumeSong(); 
    }else{
      if( (typeof(currenTrack) == 'undefined' || currenTrack == null ) && this.url == null ) return false;
      if( this.url != null ){
        this.playSong( this.title, this.url );
      }else if( (typeof(currenTrack) != null) && currentTrack != null ){
        for( var a = 0; trackOrder != null && a < trackOrder.length; a++){
          if( trackOrder[a].id == currentTrack ) {
            this.playSong( trackOrder[a].title, trackOrder[a].url );
          }
        }
      }
      this.playView();
    }
  },
  resumeSong: function(){
    this.state = this.PLAY;
    this.musicplayer.playSong();
    this.playView();
  },
  pauseSong: function(){
    this.state = this.PAUSE;
    this.musicplayer.pauseSong();
    this.pauseView();
  },
  stopSong: function(){
     this.state = this.STOP;
     this.musicplayer.stopSong();
     this.pauseView();
  },
  seek:function( percent ){
    if( percent <= 0 ) percent = 0.1;
    this.musicplayer.seekSong( percent );
  },
  setbufferbar: function( perc ){
    if( isNaN(perc) ) perc = 0;
    this.bufferbar.setStyle('width', perc+'%' );
    if( perc >= 100 ) this.buffercomplete = true;
  },
  setprogressbar: function( perc ){
    if( isNaN(perc) ) perc = 0;
    this.progressbar.setStyle('width', perc+'%' );
    var left = this.barcontainer.getCoordinates().width * (perc/100) - 10;
    this.sliderbutton.setStyle('left', left+'px' );
    if( this.track == true && perc >= 100 && this.buffercomplete ){
       this.nextSong();
    }
  },
  settime: function( position, duration ){
     position = Math.round( position );
     duration = Math.round( duration );
     var pos_sec = position % 60;
     var dur_sec = duration % 60;
     var pos_min = ( position >= 60 ) ? Math.floor( position/60 ) : 0;
     var dur_min = ( duration >= 60  ) ? Math.floor( duration/60 ) : 0;
     if(pos_sec < 10 ) pos_sec = "0"+pos_sec;
     if(dur_sec < 10 ) dur_sec = "0"+dur_sec;
     var pos = pos_min + ":" + pos_sec;
     var dur = dur_min + ":" + dur_sec;
     this.timebar.innerHTML = pos+"/"+dur;
  },
  setVolume:function( percent ){
    try{
      this.musicplayer.setVolume( percent );
    }catch(e){
    }
  }
});


function receiveBuffering( perc ){
  PLAYER.setbufferbar( perc );
}

function receiveProgress( perc ){
  PLAYER.setprogressbar( perc );
  counterr++;

}

var _counter_ = 0;
var _last_position = 0;

var colorArray = new Array();
  colorArray.push( "#000" );
  colorArray.push( "#111" );
  colorArray.push( "#222" );
  colorArray.push( "#333" );
  colorArray.push( "#444" );
  colorArray.push( "#555" );
  colorArray.push( "#666" );
  colorArray.push( "#777" );
  colorArray.push( "#888" );
  colorArray.push( "#999" );
  colorArray.push( "#AAA" );
  colorArray.push( "#BBB" );
  colorArray.push( "#CCC" );
  colorArray.push( "#DDD" );
  colorArray.push( "#EEE" );
  colorArray.push( "#FFF" );


function receiveTime( position, duration ){
  PLAYER.settime( position, duration );
}
function errorNotification(){
  var url = PLAYER.url;

  var ajax = new Ajax( null, null );
  var uri = "/media/reportbad!ajax.action?url=" + encodeURIComponent( PLAYER.url );
  ajax.get( uri, null, false );

  if( DEADLINKS.get( url ) == null ){
    dialogAlertTimeout('Song link is dead', 2000 );
    DEADLINKS.set( url, url );
  }

  PLAYER.markDead();
  PLAYER.nextSong();
  LOADEDPLAYLIST.viewcurrent();
}
function debug( msg ){
  alert( "debug: " + msg );
}

var DEADLINKS = new Hash({});
