/*
 *  Document   : radio.js
 *  Author     : Gerrit Linnemann
 *  Description: Radio-functionallity.
 *
 */

var Radio = function() {

  var channels;
  var $navigation;

  return {
    init: function(channels_) {
      channels = channels_;
      $navigation = $('#navigation');
      
      initTiles();
      console.log('Radio initialized with ' + channels.length + ' channels');
    }
  };
  
  /* private */
  function initTiles() {
    var $tileTemplate = $navigation.find('.tile.template');
  
    var counter = 1;
    while(counter <= channels.length) {
      var idx = counter - 1;
      var channel = channels[idx];
      var $tile = $tileTemplate.clone();
      
      $tile.attr('data-id', idx);
      fillTileWithChannel($tile, channel);
      addClickToTile($tile);
      
      counter++;
    }
  }
  
  /* private */
  function fillTileWithChannel($tile, channel) {
    $tile.appendTo($navigation);
    
    $tile.attr('href', channel.stream).attr('title', channel.title).attr('data-type', channel.type);
    $tile.find('.icon').attr('src', channel.icon);
    $tile.find('.title').html(channel.title).hide();
    
    $tile.hide();
    $tile.removeClass('hidden');
    $tile.fadeIn();
  }
  
  /* private */
  function addClickToTile($tile) {
    $tile.click(function(e) {
      e.preventDefault();
      
      $navigation.find('.tile').removeClass('nowplaying');
      
      var stream = $tile.attr('href');
      var idx = $tile.attr('data-id');
      console.log('Stream: ' + stream);
      
      $.ajax({
        url: '/action/play/'+idx+'/',
        context: document.body,
        statusCode: {
          200: function() {
            console.log('ok');
          },
          404: function() {
            console.log('Resource not found');
          },
          500: function() {
            console.log('Something went wrong');
          }
        }
      }).done(function() {
        $tile.addClass('nowplaying');
      });
    });
  }

}();
