$(document).ready(function(){

  function load_cover(station_name,url){
    var img = new Image();
    // wrap our new image in jQuery, then:
    $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default
      $(this).hide();
      $(this).addClass('media');
      $(this).addClass('img');
      $(this).addClass('cover-img');

      $("#"+station_name+" .infos .cover").empty()
      // with the holding div #loader, apply:
      $("#"+station_name+" .infos .cover")
      // remove the loading class (so no background spinner),
      .removeClass('loading')
      // then insert our image
      
      .append(this);

      // fade our image in to create a nice effect
      $(this).fadeIn();
    })

    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
      })

    // *finally*, set the src attribute of the new image to our image
    .attr('src',url);
  }


  function update_current_track_display(station_name){
    $.getJSON(
      "/api/"+station_name+"/current_track.json",
      function(data){
      	if ( $("#"+station_name+" .infos .hash_tag").text() != data.currentTrack.track.hash_tag){
      	  var $infos = $("#"+station_name+" .infos")
      	  $infos.fadeOut("fast");
      	  $infos.empty();
      	  $infos.hide();
      	  $infos.append('<p class="detail">En ce moment depuis <strong>'+data.currentTrack.track.last_started_at.h+'h'+data.currentTrack.track.last_started_at.m+'</strong></p><div class="cover"></div><span class="hash_tag">'+data.currentTrack.track.hash_tag+'</span><ul><li class="title">♪ '+data.currentTrack.track.title+'</li><li class="artist">'+data.currentTrack.track.artist+'</li><li class="album">'+data.currentTrack.track.album+'</li></ul>');
      	  $infos.slideDown("fast");
      	}
      }
    );
  }
  
  $("li.station").each(function(i){
    var station_name = $(this).attr("id");
    if (station_name!=null){
    update_current_track_display(station_name)
    setInterval(function(){
      update_current_track_display(station_name)
      },15*1000);
    }
  });
  
});


