document.observe('dom:loaded', function(){
  initInputs();
  if ($('rec_chars')) initRecChars();
  if ($('admin_player')) initAdminPlayer();
});

var initInputs = function() {
  
  
};

var initRecChars = function() {
  var aspect_ratio = $('aspect_ratio');
  var counter = $('rec_chars');
  var description = $('description');
    
  aspect_ratio.getAspectRatio = function() {
    this.value == '16:9' ? counter.base_chars = 240 : counter.base_chars = 172;
    counter.refresh(); 
  };
    
  counter.refresh = function() {
    this.base_chars = this.base_chars || 172;
    var new_value = this.base_chars - description.value.length;
    this.update(new_value);
  };
  
  Event.observe(aspect_ratio, 'change', function(e) {
    this.getAspectRatio();
  });
  
  Event.observe(description, 'keypress', function(e) {  
    // has to allow event to finish
    setTimeout(function(){counter.refresh();}, 1); 
  });
  
  aspect_ratio.getAspectRatio();
  
};


/*----------------------------------------------------*/
/* Work Player                                        */
/*----------------------------------------------------*/

var initAdminPlayer = function() {
  var id = $('admin_player').innerHTML;
  var url = '/work/animation/' + id;
  var work = {};
  var so;
  
  new Ajax.Request(url, { 
    method: 'get', 
    onSuccess: function(transport) { 
      data = eval("(" + transport.responseText + ")");
      work = data['work'];
      if (work.aspect_ratio == '4:3') {
       so = new SWFObject('/swfs/player.swf','player','320','240','8');
      } else {
       so = new SWFObject('/swfs/player.swf','player','400','225','8');
      }
      so.addParam('allowscriptaccess','always');
      so.addVariable('file', work.animation_url);
      so.addVariable('autostart','true');
      so.addVariable('javascriptid', 'player');
      so.addVariable('enablejs', 'true');
      console.log(so.aspect_ratio)
      so.write('admin_player');
      $('description').update(work.description);
    }
  });  
};