$(document).ready(function(){
    $('.duration').on('change mousemove input', function(){
        $(this).next().html($(this).val() + ' minutes');
    });

    $('.square').height(function(){
        return $(this).width();
    });
    $('.square').css('line-height', function(){
        return $(this).width() + 'px';
    });

    var ws_scheme = 'ws';
    if (window.location.protocol == 'https:'){
      ws_scheme = 'wss';
    }
    var ws = new WebSocket(ws_scheme + "://" + window.location.host + "/websocket");
  
    ws.onmessage = function(evt) {
      var data = JSON.parse(evt.data);
      if(data.operation == 'REFRESH'){
        location.reload();
      }
      if(data.operation == 'TRACK_CHANGE'){
        if(data.artist){
            $('.artist').html(data.artist);
        } else {
            $('.artist').html("<i>Artiste inconnu</i>");
        }
        if(data.title){    
            $('.title').html(data.title);
        } else {
            $('.title').html('<i>Titre inconnu</i>');
        }
        if(data.picture_mime && data.picture_data){
            $('.picture').html('<img src="data:' + data.picture_mime + ';base64,' + data.picture_data + '" alt="Album cover" />');
        } else {
            $('.picture').html('');
        }
      }
    };

    $('input.vertical').on('change mousemove input', function(){
        ws.send(JSON.stringify({
          name: $(this).attr('name'),
          value: $(this).val()
        }));
    });
});
