$(document).ready(function() {

  // music library  
  music = [
            {musicLink:'http://www.youtube.com/watch?v=br5jTI_SpwI',length:60*4+21,artist:'Kevin Rudolf',song:'I Made It'},
            {musicLink:'http://www.youtube.com/watch?v=mAsqZTwp1lQ',length:60*4+16,artist:'Jay-Z',song:'Forever Young'},
            {musicLink:'http://www.youtube.com/watch?v=eryimNsI02E',length:60*4+7,artist:'Rihanna',song:'Hard'},
            {musicLink:'http://www.youtube.com/watch?v=aGKt68M6DR4',length:60*3+53,artist:'ATB',song:'Sunburn'},
            {musicLink:'http://www.youtube.com/watch?v=cB5e0zHRzHc',length:60*6+14,artist:'Usher',song:'Love In This Club'},
            {musicLink:'http://www.youtube.com/watch?v=tA48ZB1YmuE',length:60*6+59,artist:'Robert Miles',song:'Fable'},
            {musicLink:'http://www.youtube.com/watch?v=f3Yp_gdAHHE',length:60*3+17,artist:'Keisha',song:'Tik Tok'},
            {musicLink:'http://www.youtube.com/watch?v=M11SvDtPBhA',length:60*3+21,artist:'Miley Cyrus',song:'Party In The Usa'},
            {musicLink:'http://www.youtube.com/watch?v=E1mU6h4Xdxc',length:60*3+21,artist:'Rihanna',song:'Disturbia'},
            {musicLink:'http://www.youtube.com/watch?v=ysSxxIqKNN0',length:60*4+26,artist:'Linkin Park',song:'New Divide'},
            {musicLink:'http://www.youtube.com/watch?v=Ejm6jn9AFA0',length:60*7+29,artist:'Darude',song:'Sandstorm'},
            {musicLink:'http://www.youtube.com/watch?v=C7ec0VI4Yl0',length:60*4+2,artist:'Young Jeezy',song:'Go Getta'},
            {musicLink:'http://www.youtube.com/watch?v=IGyp0Kc9RJM',length:60*3+50,artist:'Fort Minor',song:'Believe Me'},
            {musicLink:'http://www.youtube.com/watch?v=B-KvzFgw6sA',length:60*3+11,artist:'Linkin Park',song:'Nobody\'s Listening'},
            {musicLink:'http://www.youtube.com/watch?v=5Wh23g5Q2Z0',length:60*3+15,artist:'Three Days Grace',song:'Time of Dying'},
            {musicLink:'http://www.youtube.com/watch?v=5_LxyhCJpsM',length:60*3+16,artist:'The Offspring',song:'You\'re Gonna Go Far, Kid'},
            {musicLink:'http://www.youtube.com/watch?v=eDuRoPIOBjE',length:60*6+14,artist:'Drake, Kanye, Lil Wayne, Eminem',song:'Forever'},
            {musicLink:'http://www.youtube.com/watch?v=lL2ZwXj1tXM',length:60*3+31,artist:'Three Days Grace',song:'Never Too Late'},
            {musicLink:'http://www.youtube.com/watch?v=Lg8gEIBs5CU',length:60*4+15,artist:'3 Doors Down',song:'Kryptonite'},
            {musicLink:'http://www.youtube.com/watch?v=wZQ5f0xXvPU',length:60*5+42,artist:'Linkin Park',song:'Krwlng'},
            {musicLink:'http://www.youtube.com/watch?v=ShtAtZEMGUY',length:60*3+36,artist:'Breaking Benjamin',song:'I Will Not Bow'}
          ];


  // get the songs from the url parameters
  songNumbers = [];
  getSongs();
  //console.log(songNumbers);

  // set up the canvas  
  setDimensions();
  //get a reference to the canvas 
  context = $('#canvas')[0].getContext("2d");


  // set up useful variables
  musicIterator=0;
  numCircles=100;
  drawIterator=0;
  mode=0;
  musicPlaying=true;
  playlistOpen=false;
  
  //start music
  startMusicLoop();
  
  //set up visualization
  makeCircles();
  
  // start visualization
  setInterval(draw, 1000/60);
  setInterval(changeMode, 5000);
  
  // button click listeners
  $('div#stopMusic').click(function(){
    if(musicPlaying){
      $("div#youtube").html('');
      clearTimeout(musicTimeout);
      $(this).css("background-image","url('play.png')");
      musicPlaying=false;
    }
    else{
      $(this).css("background-image","url('stop.png')");
      musicPlaying=true;
      musicIterator=musicIterator-1;
      switchMusic();
    }
  });
  
  $('div#restartMusic').click(function(){
    musicIterator=0;
    startMusicLoop();
  });
  
  $('div#previousSong').click(function(){
    musicIterator=musicIterator-2;
    if(musicIterator<-1){
      musicIterator=songNumbers.length-2;
    }
    clearTimeout(musicTimeout);
    $('div#stopMusic').css("background-image","url('stop.png')");
    musicPlaying=true;
    switchMusic();
  });
  
  $('div#nextSong').click(function(){
    clearTimeout(musicTimeout);
    $('div#stopMusic').css("background-image","url('stop.png')");
    musicPlaying=true;
    switchMusic();
  });
  
  $('div#playlistButton').click(function(){
    if(playlistOpen){
      $('div#playlist').css("display","none");
      playlistOpen=false;
    }
    else{
      populatePlaylist();
      $('div#playlist').css("display","block");  
      playlistOpen=true;
    }
  });

});

function populatePlaylist(){
  playlistString='<table id="playlistTable">';
  
  playlistString+='<tr>';
  playlistString+='<th>#</th>';
  playlistString+='<th>Artist</th>';
  playlistString+='<th>Song</th>';
  playlistString+='</tr>';
  
  for(var i=0;i<songNumbers.length;i++){
    playlistString+='<tr class="song">';
    playlistString+='<td>'+(i+1)+'.</td>';
    playlistString+='<td>'+music[songNumbers[i]].artist+'</td>';
    playlistString+='<td>'+music[songNumbers[i]].song+'</td>';
    playlistString+='</tr>';
  }
  playlistString+="</table>";
  $("div#playlist").html(playlistString);
}

function getSongs()
{
  name='songs';
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null ){
    for(var i=0;i<music.length;i++){
      songNumbers.push(i);
    }
    return "";
  }
  else{
    songString = results[1];
    for(var i=0;i<songString.length;i++){
      songNumbers.push(parseInt( songString.substring(i,i+1) ));
    }
    return songString;
  }
}

function changeMode(){

  for(var i=0;i<numCircles;i++){
    if(mode%10==0){
      circlesDX[i]=5;
    }
    else if(mode%10==1){
      circlesDX[i]=0;
    }
    else if(mode%10==2){
      circlesDX[i]=-5;
    }
    else if(mode%10==3){
      circlesDX[i]=Math.floor(Math.random()*7);
    }
    else if(mode%10==4){
      circlesDY[i]=0;
      circlesDX[i]=0;
    }
    else if(mode%10==5){
      circlesDX[i]=-5;
    }
    else if(mode%10==6){
      circlesDX[i]=Math.floor(Math.random()*7);
    }
    else if(mode%10==7){
      circlesDX[i]=0;
    }
    else if(mode%10==8){
      circlesDY[i]=Math.floor(Math.random()*7);
    }
    else if(mode%10==9){
      circlesDY[i]=Math.floor(Math.random()*-7);
    } 
    if(mode%20==19){
      circlesDX[i]=-Math.floor((circlesX[i]-stageWidth/2)/(stageWidth/8));
      circlesDY[i]=-Math.floor((circlesY[i]-stageHeight/2)/(stageHeight/8));
    }
    if(mode%40==30){
      var diffX = circlesX[i]-stageWidth/2;
      var diffY = circlesY[i]-stageHeight/2;
      if(diffX<=0&&diffY<=0){
        circlesDX[i]=-diffX/(stageWidth/8);
        circlesDY[i]=diffY/(stageHeight/8);
      }
      else if(diffX<=0&&diffY>=0){
        circlesDX[i]=diffX/(stageWidth/8);
        circlesDY[i]=diffY/(stageHeight/8);
      }
      else if(diffX>=0&&diffY>=0){
        circlesDX[i]=diffX/(stageWidth/8);
        circlesDY[i]=-diffY/(stageHeight/8);
      }
      else if(diffX>=0&&diffY<=0){
        circlesDX[i]=-diffX/(stageWidth/8);
        circlesDY[i]=-diffY/(stageHeight/8);
      }
    }
  }
  mode=mode+1;
  
}

function setDimensions(){
  stageWidth=$(document).width();
  //stageHeight=$(document).height()-$('div#content-header').height()-$('div#seperator').height();
  stageHeight=$(document).height();
  $('canvas').attr("width",String(stageWidth));
  $('canvas').attr("height",String(stageHeight));
}

function makeCircles(){
  circlesX=[];
  circlesY=[];
  circlesDX=[];
  circlesDY=[];
  circlesRed=[];
  circlesGreen=[];
  circlesBlue=[];
  circlesR=[];
  circlesDR=[];
  circlesTimer=[];
  for(var i=0;i<numCircles;i++){
    circlesX.push( Math.floor(Math.random()*(stageWidth+1)) );
    //circlesY.push( Math.floor(Math.random()*(stageHeight+1)) );
    circlesY.push( stageHeight/2 );
    //circlesDX.push( Math.floor(Math.random()*6)-3 );
    //circlesDY.push( Math.floor(Math.random()*6)-3 );
    circlesDX.push( 0 );
    circlesDY.push( 0 );
    circlesRed.push( Math.floor(Math.random()*256) );
    circlesGreen.push( Math.floor(Math.random()*256) );
    circlesBlue.push( Math.floor(Math.random()*256) );
    //circlesR.push( Math.floor(Math.random()*11) );
    circlesR.push( Math.floor(Math.random()*11) );
    circlesDR.push( -.25 );
    circlesTimer.push( Math.floor(Math.random()*101) );
  }
}

function draw() {
  context.clearRect(0,0,stageWidth,stageHeight);

  for(var j=0;j<numCircles;j++){
  
    // spatial boundary testing
    if(circlesX[j]<0)
      circlesX[j]=stageWidth;
    else if(circlesX[j]>stageWidth)
      circlesX[j]=0;
    if(circlesY[j]<0)
      circlesY[j]=stageHeight;
    else if(circlesY[j]>stageHeight)
      circlesY[j]=0;
      
    // radial boundary testing
    if(circlesR[j]>Math.floor(Math.random()*6)+25){
      circlesDR[j]=-1;
      circlesTimer[j]=100;
    }
    else if( circlesR[j]<Math.floor(Math.random()*4)+3 && circlesTimer[j]>0 ){
      circlesDR[j]=0;
      circlesTimer[j]=circlesTimer[j]-1;
    }
    else if( circlesR[j]<Math.floor(Math.random()*4)+3 && circlesTimer[j]<=0 ){
      circlesDR[j]=10;
    }
  
    var tmp_gradient = context.createRadialGradient(circlesX[j], circlesY[j], 0, circlesX[j], circlesY[j], circlesR[j]);
    tmp_gradient.addColorStop(0, "rgba("+circlesRed[j]+","+circlesGreen[j]+","+circlesBlue[j]+","+1+")" );
    tmp_gradient.addColorStop(1, "rgba("+circlesRed[j]+","+circlesGreen[j]+","+circlesBlue[j]+","+0+")" );
    context.fillStyle = tmp_gradient;
    
    context.beginPath();
    //console.log(j+" "+circlesX.length+" "+circlesY.length+" "+circlesR.length);
    context.arc(circlesX[j], circlesY[j], circlesR[j], 0,Math.PI*2,true);
    context.closePath();
    context.fill();

    
    // changing variables
    circlesX[j]=circlesX[j]+circlesDX[j];
    circlesY[j]=circlesY[j]+circlesDY[j];
    circlesR[j]=circlesR[j]+circlesDR[j];      

  }
  drawIterator=drawIterator+1;
}

function startMusicLoop(){
  $("div#youtube").html('<iframe src ="'+music[songNumbers[0]]['musicLink']+'" width="0" height="0"><p>Your browser does not support iframes.</p></iframe>');
  $("div#nowPlaying").html('Now Playing: '+music[songNumbers[0]]['song']+' By: '+music[songNumbers[0]]['artist']);
  musicTimeout = setTimeout("switchMusic()",1000*music[songNumbers[0]]['length']);
}

function switchMusic(){
  if(musicIterator<songNumbers.length-1){
    musicIterator=musicIterator+1;
    $("div#youtube").html('<iframe src ="'+music[songNumbers[musicIterator]]['musicLink']+'" width="0" height="0"><p>Your browser does not support iframes.</p></iframe>');
    $("div#nowPlaying").html('Now Playing: '+music[songNumbers[musicIterator]]['song']+' By: '+music[songNumbers[musicIterator]]['artist']);
    musicTimeout = setTimeout("switchMusic()",1000*music[songNumbers[musicIterator]]['length']);
  }
  else{
    musicIterator=-1;
    switchMusic();
  }
}
