var ARTISTNAME = "";
var firstVideoLoad = true;
var rotatMusicInterval;
var showMusicInterval;
var playerstartinterval;
var ACTIVEPLAY = null;
var player_open = false;
var ORIGINAL_BIO_HEIGHT = 275;
var SIMILAR_ARTIST_COUNT = 5;
var showSimilarArtistInterval;

function loadPipes(){
  var flashvars = {};
  var params = { wmode: "transparent", allowScriptAccess:"always" };
  var attributes = { id: "yahoopipes1", name: "yahoopipes1" };
  swfobject.embedSWF( statichost + "/swf/YahooPipes.swf", "yahoopipes", "1", "1", "9.0.0", null, flashvars, params, attributes);
}

function loadArtistNews( artistName ){
  var flashvars = {};
  var params = { wmode: "transparent", allowScriptAccess:"always" };
  var attributes = { id: "artistnewsflash", name: "artistnewsflash" };
  swfobject.embedSWF( statichost + "/swf/artist_output_news.swf?artist=" + artistName,
                      "artistnewcode", "1", "1", "8.0.0", null, flashvars, params, attributes);
}

function getSimilarArtist( count ){
  if( count != null ) SIMILAR_ARTIST_COUNT = count;
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  var pipeSWF = (isIE) ? window["yahoopipes1"] : document["yahoopipes1"];
  if( pipeSWF != null && pipeSWF.getPipe != null ){
     clearInterval( showSimilarArtistInterval );
     var uri = "http://pipes.yahooapis.com/pipes/pipe.run?_id=BGsSxZ0s3hGcdngx1ZzWFw&_render=json&api_key=1041a79eaa100bb1ab5be738a5c4e2f2&" +
               "artist=" + encodeURIComponent( ARTISTNAME );
     var callback = "showSimilarArtist";
     pipeSWF.getPipe( uri, callback );
  }
}

function showSimilarArtist( content, code ){
  if( code == "true" ){
    var json = eval( '(' + content + ')' );

    var items = json.value.items;
    if( items != null ){
      var list = items[0].artist;
      var artistlist = [];
      for( var a = 1; list != null && a < list.length; a++ ){
        if( list[a] != null ) artistlist.push( list[a] );
      }
      shuffle( artistlist );
      var html = '<table id="similar_artist_table" width="100%"><tr>';

      for( var a = 0; a < artistlist.length && a < SIMILAR_ARTIST_COUNT; a++ ){
        var imagelist = artistlist[a].image;       
        var image = imagelist[1].content;
        var name  = artistlist[a].name;
        html += '<td style="text-align:center">' +
                '<table class="image" align="center"><tr><td><div>'+
                '<a href="/artist/' + name + '">'+
                '<img alt="'+ name +'" src="' + image + '">'+
                '</a></div></td></tr></table>' + 
                '<a class="palebluelink" href="/artist/' + name + '">'+ name + '</a>' +
                '</td>';
      }
      if( artistlist.length == 0 ){
        html += '<td style="text-align:center">No Similar Artist Known</td>';
      }
      html += '</tr></table>';
      $('similar_artist_output').innerHTML = html;
    }else{
      var html = '<div style="text-align:center">No Similar Artist Known</div>';
      $('similar_artist_output').innerHTML = html;
    }
  }
}


function getMusicNewsError(){
     $('news_console').innerHTML = "Error Retrieving News Feed";
}

function getMusicNews( jsont ){
    var json = eval( '(' + jsont + ')' );
    if( json == null || json.length == 0 ){
      $('news_console').innerHTML = "No news feed for artist";
      return;
    }
    var html = '<table id="news_table" cellpadding="0" cellspacing="0" width="100%">';
    for( var a = 0; a < json.length; a++ ){
      json[a].id = a;
      var re = new RegExp("(.*?), (\\d+) (\\S+) (\\d+) .*");
      var m = re.exec(json[a].pubDate);
      var date;
      if( m == null ) date = json[a].pubDate;
      else date = m[3] + " " + m[2] + " " + m[4];
      html += '<tr><td width="100">' + date+ '</td>'+
              ' <td class="news" i="'+ a + '"><div class="titleoverflow">'+
              '  <a class="palebluelink" href="'+ json[a].link + '" target="_blank">'+ json[a].title + '</a>'+
              ' </div></td><td width="40">&nbsp;</td></tr>';
    }
    html += '</table>'
    $('news_console').innerHTML = html;

    $$('#news_table .news').each( function(el){
      el.addEvent( 'mouseover', function( event, news ){
        showNewBubble( news, event );
      }.bindWithEvent( el , json[el.getAttribute("i")] ) );
    });
    $$('#news_table .news').each( function(el){
      el.addEvent( 'mouseout', function( event, news ){
        hideNewBubble( news );
      }.bindWithEvent( el , json[el.getAttribute("i")] ) );
    });

    new ScrollBar().init('news_container','news_console','news_slider_bar');
}


function hideNewBubble( news ){
    if( $('news'+news.id) ){
       document.getElementsByTagName("body")[0].removeChild( $('news'+news.id) );
    }
}

function showNewBubble( news, event ){
    var x = event.page.x + 10;
    var y = event.page.y + 5;
    var div = $(document.createElement('div'));
    div.setAttribute('class', 'newsbubble');
    div.setAttribute('className', 'newsbubble');
    div.setAttribute('id', 'news'+news.id );
    div.setStyle('position', 'absolute');
    div.setStyle('top', y+'px');
    div.setStyle('left', x+'px');

    var title = $(document.createElement('div'));
    title.setAttribute('class', 'newsbubble_title');
    title.setAttribute('className', 'newsbubble_title');
    title.innerHTML = news.title;

    var content = $(document.createElement('div'));
    content.setAttribute('class', 'newsbubble_content');
    content.setAttribute('className', 'newsbubble_content');
    content.innerHTML = news.description;

    div.appendChild( title );
    div.appendChild( content );

    document.getElementsByTagName("body")[0].appendChild( div );
}

function getMusicVideo(){
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    var pipeSWF = (isIE) ? window["yahoopipes1"] : document["yahoopipes1"];
    if( pipeSWF != null && pipeSWF.getPipe != null ){
       clearInterval( showMusicInterval );
       var uri = "http://pipes.yahooapis.com/pipes/pipe.run?_id=jpG_8KB_3RGNGO1Epl8axw&_render=json&max-results=10&query=" + encodeURIComponent( ARTISTNAME );
       var callback = "showMusicVideo";
       pipeSWF.getPipe( uri, callback );
    }
}

function showMusicVideo( content, code ){
    if( code == "true" ){
      var tdwidth = 128;
      var json = eval( '(' + content + ')' );
      var videos = json.value.items;
      if( firstVideoLoad ){
        firstVideoLoad = false;
        rotatMusicInterval = setInterval( "getMusicVideo()", 60*1000 );
      }else videos = shuffle( videos );

      var obj;
      for( var a = 0; a < videos.length; a++ ){
        obj = new Object();
        obj.link = videos[a].link;
        obj.title = videos[a].title;
        obj.description = videos[a].description;
        obj.duration = videos[a]['media:group']['yt:duration'].seconds;

        var duration = parseInt( obj.duration );
        var min = Math.floor( duration / 60 );
        var secs = duration % 60;
        if( min < 10 ) min = "0"+min;
        if( secs < 10 ) secs = "0"+secs;
        obj.time = min+":"+secs;

        var thumbnails = videos[a]['media:group']['media:thumbnail'];
        for( var b = 0; b < thumbnails.length; b++ ){
          if( thumbnails[b].url.match(/1.jpg/) ){
             obj.thumbnail_url = thumbnails[b].url;
             $('music_video_'+(a+1)).innerHTML = '<img src="'+thumbnails[b].url+'" width="100">';
             $('music_video_'+(a+1)).removeEvents();
             $('music_video_'+(a+1)).addEvent('mouseover', function(o){               
               $('music_video_details').setStyle('display', 'block');
               var fx = new Fx.Morph( $('music_video_details'), {duration: 500, transition: Fx.Transitions.linear });
               fx.start({ left:0, top:0, opacity:1 }).chain( function(){
                 $('music_video_detail_image').innerHTML = '<img src="'+o.thumbnail_url+'" width="120">';
                 $('music_video_detail_time').innerHTML = "Length: " +  o.time;

                 $('music_video_detail_add').setStyle('cursor', 'pointer');
                 $('music_video_detail_add').removeEvents();
                 $('music_video_detail_add').addEvent('click', function( o2 ){
                   global_addsong( o2.title, o2.link );
                 }.pass( o ));


                 $('music_video_detail_play').setStyle('cursor', 'pointer');
                 $('music_video_detail_play').removeEvents();
                 $('music_video_detail_play').addEvent('click', function( o2 ){
                   playSong( o2.link, o2.title, null );
                   var fx = new Fx.Morph( $('music_video_details'), {duration: 500, transition: Fx.Transitions.linear });
                   fx.start({ left:590, top:0, opacity:1 }).chain( function(){
                     $('music_video_detail_content').setStyle('opacity', 0);
                   });
                 }.pass( o ) );

                 $('music_video_detail_description').innerHTML = ""+
                   '<span style="font-size:10pt"><b>'+o.title+'</b></span><p>'+o.description;
                 fx = new Fx.Morph( $('music_video_detail_content'), {duration: 500, transition: Fx.Transitions.linear });
                 fx.start({ opacity:1 });
               });
             }.pass( obj ) );
          }
        }
      }
    }
}

function initmusicvideobar(){
  if( $('music_video_details') ){
    $('music_video_details').addEvent('mouseout', function(e){
      var top = $('music_videos_mask').getCoordinates().top;
      var bottom = top + $('music_videos_mask').getCoordinates().height;
      var left= $('music_videos_mask').getCoordinates().left;
      var right = left + $('music_videos_mask').getCoordinates().width;
      var x = e.page.x;
      var y = e.page.y;
      if( left <= x && x <= right && top <= y && y <= bottom ){
      }else{
        var fx = new Fx.Morph( $('music_video_details'), {duration: 500, transition: Fx.Transitions.linear });
        fx.start({ left:590, top:0, opacity:1 }).chain( function(){
          $('music_video_detail_content').setStyle('opacity', 0);
        })
      }
    });
  }
}


var shuffle = function(o){
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
       return o;
};

var Player = new Class({
  initialize: function(){
    this.attemped = false;
    this.started = false;
    this.state = 0;
    this.STOP = 1;
    this.PAUSE = 2;
    this.PLAY = 3;
    this.url = null;
    this.bufferbar   = $('bufferbar');
    this.progressbar = $('progressbar');
    this.seekbar     = $('seekbar');
    this.pausebutton  = $('pausebutton');
    this.playbutton = $('playbutton');
    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.pausebutton.addEvent('click', function(_player){ _player.pauseSong();  }.pass( this ) );
    this.playbutton.addEvent('click', function( _player){  _player.unpauseSong();  }.pass( this ) );
    this.seekbar.addEvent('click', handlerseek.bindWithEvent( this.seekbar , this ) );
    this.initflash();
  },
  initflash : function(){
    if( this.started == true ) return;
    if( this.attemped == false ){
      this.attemped = true;      
      var lc = generateLine();

    
      //var viewer_url = statichost + "/swf/MediaConsoleViewer.swf?lc=1";
      //var controller_url = statichost + "/swf/MediaConsoleController.swf?lc=1"; 
      var viewer_url = statichost + "/swf/Viewer.swf?lc=1";
      var controller_url = statichost + "/swf/Controller.swf?lc=1";

      var flashvars = {};
      var params = { wmode: "transparent", allowScriptAccess:"always", quality:"high" };
      var attributes = { id: "audioplayer", name: "audioplayer" };
      swfobject.embedSWF( controller_url, "playercode_controller", "1", "1", "8.0.0", statichost + "/swf/expressInstall.swf", flashvars, params, attributes);

      flashvars = {};
      params = { wmode: "transparent", allowScriptAccess:"always", quality:"high" };
      attributes = { id: "audioplayer_viewer", name: "audioplayer_viewer" };
      swfobject.embedSWF( viewer_url, "playercode", "147", "110", "8.0.0", statichost + "/swf/expressInstall.swf", flashvars, params, attributes);

    }
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    this.musicplayer = (isIE) ? window["audioplayer"] : document["audioplayer"];
    if( typeof(this.musicplayer) != "undefined"  ){
      this.started = true;
      $('player_container').setStyle('visibility', 'hidden' );
//      $('player_container').setStyle('opacity', 0 );
//      var fx = new Fx.Morph( $('player_container'), {duration: 500, transition: Fx.Transitions.linear });
//      fx.start({ left:0, t

    }
  },
  playSong: function( title, url ){
    this.initflash();
    if( ! this.started ){
      dialogAlertTimeout('Sorry the Player is still loading. Try Again', 1000 );
      return;
    }
    this.url = url;
    this.pausebutton.setStyle('display', 'block');
    this.playbutton.setStyle('display','none');
    this.state = this.PLAY;
    this.setbufferbar( 0 );
    this.setprogressbar( 0 );
    this.musicplayer.loadSong( title, url );
  },
  pauseSong: function(){
    this.initflash();
    if( ! this.started ){
      dialogAlertTimeout('Sorry the Player is still loading. Try Again', 1000 );
      return;
    }
    this.pausebutton.setStyle('display', 'none');
    this.playbutton.setStyle('display','block');
    this.musicplayer.pauseSong();
  },
  unpauseSong: function(){
    this.initflash();
    if( ! this.started ){
      dialogAlertTimeout('Sorry the Player is still loading. Try Again', 1000 );
      return;
    }
    this.pausebutton.setStyle('display', 'block');
    this.playbutton.setStyle('display','none');
    this.musicplayer.playSong();
  },
  stopSong: function(){
     this.state = this.STOP;
     this.musicplayer.stopSong();
  },
  seek:function( percent ){
    if( percent <= 0 ) percent = 0.1;
    this.musicplayer.seekSong( percent );
  },
  setbufferbar: function( perc ){
    if( this.bufferbar == null ) return;
    if( isNaN(perc) ) perc = 0;
    this.bufferbar.setStyle('width', perc+'%' );
    this.seekbar.setStyle('width', perc+'%' );
    if( perc >= 100 ) this.buffercomplete = true;
  },
  setprogressbar: function( perc ){
    if( this.progressbar == null ) return;
    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' );
  }
});

function checkPlayerStart(){
  PLAYER.initflash();
  if( PLAYER.started == true){
    clearInterval(playerstartinterval);
    $('player_container').setStyle('visibility', 'hidden');
  }
}

function receiveBuffering( perc ){
  PLAYER.setbufferbar( perc );
}
function receiveProgress( perc ){
  PLAYER.setprogressbar( perc );
}
function receiveTime( position, duration ){
  PLAYER.settime( position, duration );
}
function errorNotification(){
   dialogAlertTimeout('Song link is dead', 2000 );
   var ajax = new Ajax( null, null );
   var uri = "/media/reportbad!ajax.action?url=" + encodeURIComponent( PLAYER.url );
   ajax.get( uri, null, false );
}


function closePlayer(){
  if( ! player_open ) return;
  var fx = new Fx.Morph( $('player_container'), {duration: 500, transition: Fx.Transitions.linear });
  fx.start({ opacity:0 }).chain( function(){
    $('player_container').setStyle('visibility', 'hidden');
  });
  player_open = false;
}

function showPlayer( url, title ){
  if( player_open ) return;
  $('player_container').setStyle('opacity', 0);
  $('player_container').setStyle('visibility', 'visible');
  $('player_container_add').removeEvents();
  $('player_container_add').addEvent( 'click', function(o){
    addSong( o.url, o.title );
  }.pass( { 'url':url, 'title':title } ) );


  var fx = new Fx.Morph( $('player_container'), {duration: 500, transition: Fx.Transitions.linear });
  fx.start({ opacity: 1 });
  player_open = true;
}

function playSong( url, title, button ){
  var re = new RegExp("http://www\.youtube\.com/watch\\?v=(.*)");
  if( re.exec(url) != null ){
    showPlayer( url, title );
  }else{
    closePlayer();
  }

  if( ACTIVEPLAY == null ){
    ACTIVEPLAY = new Object();
  }else if( typeof(ACTIVEPLAY.button) != 'undefined' && ACTIVEPLAY.button != null ){
    ACTIVEPLAY.button.onmouseover = ACTIVEPLAY.onmouseover;
    ACTIVEPLAY.button.onmouseout  = ACTIVEPLAY.onmouseout;
    ACTIVEPLAY.button.onmouseout();
  }
  if( ACTIVEPLAY != null && ACTIVEPLAY.button == button && button != null){
    PLAYER.stopSong();
    ACTIVEPLAY.button      = null;
    return;
  }
  if( button != null ){
    ACTIVEPLAY.button      = button;
    ACTIVEPLAY.onmouseover = button.onmouseover;
    ACTIVEPLAY.onmouseout  = button.onmouseout;
    button.onmouseover     = null;
    button.onmouseout      = null;
    ACTIVEPLAY.onmouseout();
  }

  PLAYER.playSong( title, url );
}


function addSong( url, title ){
  global_addsong( title, url );
}

function resizeImage(){
  var image = $('artist-image');
  var MAX_HEIGHT = 350; //350
  var MAX_WIDTH  = 250; //250
  var height = image.getCoordinates().height;
  var width  = image.getCoordinates().width;
  if( height > MAX_HEIGHT || width > MAX_WIDTH ){
    var w_perc = MAX_WIDTH / width;
    var h_perc = MAX_HEIGHT / height;
    var perc = ( w_perc > h_perc ) ? h_perc : w_perc;
    image.setStyle('height', (height*perc) + 'px' );
    image.setStyle('width', (width*perc) + 'px' );
  }
}

function resizeBio(){
  var div = $('aritst-bio');
  var MAX_HEIGHT = 275;
  var height = div.getCoordinates().height;
  ORIGINAL_BIO_HEIGHT = height;
  if( height > MAX_HEIGHT ){
    $('showmore').setStyle('display', 'block');
    div.setStyle('overflow', 'hidden');
    div.setStyle('height', MAX_HEIGHT + 'px');
  }
}

function showallBio(){
  var div = $('aritst-bio');
  var fx = new Fx.Morph( div, {duration: 1000, transition: Fx.Transitions.linear });
  fx.start({ height: ORIGINAL_BIO_HEIGHT });
  $('showmore').setStyle('display', 'none' );
}

