var players = {};
var player_states = {};
var player_ctl_texts = {};

function stateTracker(obj) {
   switch (obj.newstate) {
      case "PLAYING" :
          for (var i in player_states) {
             if (player_states[i] == true) {
                players[i].sendEvent('STOP');
                player_states[i] = false;
             }
          }
         togglePlayerCtl(obj.id+"_ctl", true);
         player_states[obj.id] = true;
      break;
      default:
         togglePlayerCtl(obj.id+"_ctl", false);
      break;
   }
   //alert('the playback state is changed from '+obj.oldstate+' to '+obj.newstate);
};

function playerReady(thePlayer) {
   players[thePlayer.id] = window.document[thePlayer.id];
   players[thePlayer.id].addModelListener("state", "stateTracker");
   player_states[thePlayer.id] = false;
}

function togglePlayerCtl(ctl_id, state) {
   var texts = player_ctl_texts[ctl_id];
   if (state == false) {
      $("#"+ctl_id).html(texts[0]);
      $("#"+ctl_id).css("background-position", "0px 2px");
   } else {
      $("#"+ctl_id).html(texts[1]);
      $("#"+ctl_id).css("background-position", "0px -147px");
   }
}

function createPlayer(playerId, placeholderId, videofile, splashscreen, starttext, stoptext) {
   player_ctl_texts[playerId + "_ctl"] = [starttext, stoptext];
   player_states[playerId] = false;
   var flashvars = {
      image:splashscreen,
      file:videofile,
      autostart:"false",
      bgcolor:'#CCCCCC',
      controlbar:'none'
   }
   var params = {
      allowfullscreen:"true",
      allowscriptaccess:"always"
   }
   var attributes = {
      id:playerId,
      name:playerId
   }
   swfobject.embedSWF("/static/flash/flvplayer_4.3.swf", placeholderId, "205", "136", "9.0.115", false, flashvars, params, attributes);
}
function togglePlayer(sender, playerId) {
   var ctl_id = playerId + "_ctl";
   if (player_states[playerId] == true) {
      players[playerId].sendEvent('STOP');
      togglePlayerCtl(ctl_id, false);
   } else {
      players[playerId].sendEvent('PLAY');
      togglePlayerCtl(ctl_id, true);
   }
}

