$(document).ready(function(){

  // add click handler on tabs, to refresh the tab content
  var blocksModules = Drupal.settings.aefPlayer.remote.blocks; 
  for (key in blocksModules) {
    $('#block-aef_player-'+ blocksModules[key] +' .tabs a.tab').click(function(context) {
      aef_remote_set_tab(this.id);
      return false;
    });
  }
  // We fake a click on the active tab to bind the play action
  //$('#block-aef_player-'+ blocksModules[key] +' .tabs a.active').click();
  // regularly refresh tab content
  $(document).everyTime(600000, function(i) {aef_remote_refresh_blocks();});

  // create a slave FlashBridge instance
  window.FlashBridgeInstance = new window.FlashBridgeClass();
  window.FlashBridgeInstance.swfPath = Drupal.settings.aefPlayer.flashBridgePath;
  //window.FlashBridgeInstance.jsCallbackPrefix = Drupal.settings.aefPlayer.playerId;
  window.FlashBridgeInstance.connectionNamePrefix = Drupal.settings.aefPlayer.playerId;
  window.FlashBridgeInstance.setCallbacks({
    "called":function(method,params) {
      window.france24_slave_remoteAPI[method].apply(window.FlashBridgeInstance,params);
    },
    "ready":function() {
      //console.log("ready!");
      if (window.location.hash == '#player' || Drupal.settings.aefPlayer.autoOpen) {
        $('.block-aef_player h3.title a').click();
      }
    }
  });

  var params = {};
  if(Drupal.settings.aefPlayer.flashBridgeColor != undefined)
    params = {bgcolor: Drupal.settings.aefPlayer.flashBridgeColor};
  window.FlashBridgeInstance.insert(false, params);

  
  // insert slider @TODO: use better method than a timer
  $(document).oneTime(2000, function(i) {
    aef_remote_build_controls();
    if (window.FlashBridgeInstance.masterConnected) {
      $('#block-aef_player-'+ blocksModules[key] +' .controls').show();
      window.FlashBridgeInstance.sendToMaster("getData", []);
    }
  });
  
  // security: if the controlbar is not closed when closing popup: check regularly if master is connecter
  $(document).everyTime(5000, function() {
    if (!window.FlashBridgeInstance.masterConnected) {
      window.france24_slave_remoteAPI.close();
    }
  });
  
  // add a click handler on links containing the site URL, and finishing with #player
  $('a[href$=#player]').live('click', function () {
    if (this.href.match(String(window.location))) {
      $('.block-aef_player h3.title a').click();
    }
  });
  
});

function aef_remote_refresh(tabId, newTab, blockDelta) {
  if (!tabId) {
    //alert('error: tabId is empty');
  }
  if (!blockDelta) {
    blockDelta = $('#'+ tabId).parents('.block-aef_player').eq(0).attr('id').substr(17);
  }

  if (newTab || Drupal.settings.aefPlayer.remote.tabs[tabId].server_refresh) { // server refresh
    var data = $.getJSON(Drupal.settings.basePath + 'aef_player_remote', { 'module' : blockDelta, 'id': tabId },
      function(data) {
        //alert(String(data) === "[object Object]");
        //if (String(data) === "[object Object]") {
          for (key in data) {
            $('#block-aef_player-'+ blockDelta +' .content '+ key).html(data[key]);
          }
        /*}
        else {
          $('#block-aef_player-'+ blockDelta +' .content .tab-content').html(data);
          
          // get the id of the tab
          var linkid = tabId.match(/aef_remote_tab_(.*)?/);
          $('.tab-content .'+linkid[1]).click(function () {
            var tab = Drupal.settings.aefPlayer.remote.tabs[linkid[1]];
            
            window.FlashBridgeInstance.api_play(tab['url'], tab['type'], tab['title'], tab['streamer']);
            return false;
          });

        }*/
      }
    );
  }/*
  else { // client refresh: ask the player what it is playing
    // @TODO
  }*/
}

function aef_remote_set_tab(tabId) {
  aef_remote_refresh(tabId, 1);
  $('#'+ tabId).parents('.tabs').eq(0).children('.tab.active').removeClass('active');
  $('#'+ tabId).addClass('active');
}

function aef_remote_refresh_blocks() {
  var blocksModules = Drupal.settings.aefPlayer.remote.blocks; 
  for (var i = 0; i < blocksModules.length; i++) {
    tabId = $('#block-aef_player-'+ blocksModules[i] +' .tabs a.tab.active').attr('id');
    aef_remote_refresh(tabId, 0, blocksModules[i]);
  }
}

function aef_remote_build_controls() {
  $('.controlbar #progress .slider').slider({'animate': true, 'range': 'min'});
  $('.controlbar #volume .slider').slider({'range': 'min', 'value': 100});

  $('.controlbar #progress .slider').bind('slide', function (event, ui) {
  //console.log(ui);
    window.FlashBridgeInstance.api_seek(ui.value);
  });
  $('.controlbar #volume .slider').bind('slidechange', function (event, ui) {
    window.FlashBridgeInstance.api_volume(ui.value);
  });
  $('.controlbar #play a').click(function() {
    window.FlashBridgeInstance.api_pause();
    return false;
  });
  $('.controlbar #stop a').click(function() {
    window.FlashBridgeInstance.api_stop();
    return false;
  });
  $('.controlbar #mute a').click(function() {
    window.FlashBridgeInstance.api_mute();
    return false;
  });
  
}
;