var UnifiedUploader = Behavior.create({
  initialize: function() {
    this.unified_uploader = this.element;
    this.unified_uploader.observe("unified_uploader:change-content", this.changeContent.bindAsEventListener(this));
    this.form = this.unified_uploader.down('form');
    var originalFormSubmit = this.form.submit.bind(this.form);
    this.form.submit = this.submitForm.bindAsEventListener(this, originalFormSubmit);

    this.content_type_buttons = this.unified_uploader.select(".content_types li");
    this.close_buttons = this.unified_uploader.select(".upload h4 .close");
    this.content_types = this.content_type_buttons.map(function(element){ return element.getAttribute("class"); });

    this.spinner = this.unified_uploader.previous('.unified_uploader_spinner');
    this.submit_button = this.unified_uploader.down('a.submit');
    this.form.observe("submit", this.form.submit);
    this.submit_button.observeExclusively("click", this.form.submit);

    Application.MessageBus.register('iframeLoaded', this, this.handleResponse.bind(this));
    this.registerContentTypeButtons();
    this.registerCloseButtons();
    
    Video.pending_upload(this.disableSubmit.bind(this));
    Video.no_pending_upload(function(){
      this.enableSubmit();
      this.removeErrorMessages();
    }.bind(this));
    Video.is_uploading(this.enableSubmit.bind(this));
    Video.after_uploaded(this.enableSubmit.bind(this));
    Video.remove_errors = this.removeErrorMessages.bind(this);
  },

  enableSubmit: function(){
    this.submit_button.removeClassName('disabled');
  },
  
  disableSubmit: function(){
    this.submit_button.addClassName('disabled');
  },
  
  removeErrorMessages: function(){
    $$('.unified_uploader .upload.'+this.contentType()+' .errors')[0].update("");
  },

  submitForm: function(e, originalFormSubmit){
    // Ensure tinyMCE editors are dispatched since changing the default
    // form.submit function in #initialize above hinders tinyMCE's ability
    // to bind to the form submission. This ensures tinymce is able to copy
    // its contents to the proper input-field/textarea in RW
    if(tinyMCE.activeEditor){
      tinyMCE.activeEditor.onSubmit.dispatch();
    }
    
    if(this.submit_button.hasClassName('disabled')) return false;
    if(this.uploadContent()){
      if(this.contentType() == "video") {
        Video.when_uploaded(function(new_video_file_id){
          this.enableSubmit();
          // Set hidden value with a newly uploaded video_file_id. If a new
          // video wasn't uploaded this leaves the original video file id
          // in the form alone.
          if(new_video_file_id){
            this.form.down("input[type=hidden][name*=video_file_id]").setValue(new_video_file_id);
          }
          originalFormSubmit();
        }.bind(this));
      }else{
        originalFormSubmit();
      }
    }
    if(e) e.stop();
    return false;
  },

  uploadContent: function(){
    var uploadPanel = this.uploadPanel();
    if (uploadPanel) {
      var method = uploadPanel.getAttribute("data-method");
      var action = uploadPanel.getAttribute("data-action");
      this.form.setAttribute("action", action);
      this.form.down("input[type=hidden][name=_method]").setValue(method);
    }

    this.showSpinner();

    return true;
  },

  changeContent: function(event, targetContent){
    if(event && event.memo){ targetContent = event.memo; }
    this.hideUploadPanels();
    this.unified_uploader.addClassName(targetContent);
    this.unified_uploader.setAttribute('data-content-type', targetContent);
    var data_method = this.uploadPanel().getAttribute("data-method");
    this.unified_uploader.addClassName(data_method + "_button");
    
    if(this.shouldDisableSubmitButton()) 
      this.disableSubmit();
    
    this.submit_button.show();
  },
  
  shouldDisableSubmitButton: function(){
    if(this.contentType() == "video" ) return this.uploadPanel().getAttribute("data-new-record") == "true";
    return false;
  },

  error: function(error) {
    var uploadPanel = this.uploadPanel();
    var errors = uploadPanel.down('.errors');
    errors.update(Element.fromHTML(error));
  },

  registerCloseButtons: function(){
    this.close_buttons.each(function(button){
      button.observeExclusively("click", this.hideUploadPanels.bind(this));
    }.bind(this));
  },

  registerContentTypeButtons: function(){
    this.content_type_buttons.each(function(button){
      button.observeExclusively("click", this.changeContent.bindAsEventListener(this, button.getAttribute("class")));
    }.bind(this));
  },

  hideUploadPanels: function(){
    this.unified_uploader.select('.errors').invoke('update', '');
    this.content_types.each(function(className){
      this.unified_uploader.removeClassName(className);
    }.bind(this));
  },

  uploadPanel: function() {
    return this.form.down(".upload." + this.contentType());
  },

  contentType: function() {
    return this.unified_uploader.getAttribute('data-content-type');
  },

  handleResponse: function(data) {
    if(data.error){
      this.error(data.error);
      this.hideSpinner();
    }
    if(data.video_upload_error){
      this.error(data.video_upload_error);
      this.hideSpinner();
      Video.pending_upload();
    }
    if(data.redirectTo){
      window.location.href = data.redirectTo;
    }
    if(data.redirectIframe){
      this.unified_uploader.down('iframe#panda_uploader').src = data.redirectIframe;
    }
  },

  showSpinner: function(){
    this.spinner.clonePosition(this.unified_uploader);
    this.unified_uploader.setOpacity(0.25);
    this.spinner.show();
  },

  hideSpinner: function(){
    this.spinner.hide();
    this.unified_uploader.setOpacity(1);
  }
});

UnifiedUploader.mediaBrowserPath = function(){
 $$('.unified_uploader').detect(function(el){

 });
};

UnifiedUploader.Collaborator = Behavior.create({
  initialize: function(){
    this.collaborators = this.element;
    this.collaborators.down('a.button').observeExclusively('click', this.addCollaborator.bind(this));
    this.labels = this.collaborators.down('.labels');
    this.collaborations = this.collaborators.down('.collaborations');
    this.template = this.collaborations.down('.template').remove().innerHTML;

    this.collaborations.select('.collaboration').each(function(collaboration){
      this.initializeEntry(collaboration);
    }.bind(this));
  },

  addCollaborator: function(){
    var template_str = this.template.replace(/NEW_RECORD/g, this._nextIndex());
    var entry = Element.fromHTML(template_str);
    this.initializeEntry(entry);
    this.collaborations.insert({ bottom: entry });
    this.labels.show();
    Event.addBehavior.reload();
  },

  initializeEntry:function(entry){
    entry.down('a.remove').observeExclusively('click', this.removeEntry.bind(this, entry));
  },

  removeEntry:function(entry){
    entry.remove();
    if(this.collaborations.select(".collaborator").size() == 0){
      this.labels.hide();
    }
  },

  _nextIndex: function(){
    if(this.index){ this.index--; }
    else { this.index = -1; }
    return this.index;
  }
});

UnifiedUploader.Credits = Behavior.create({
  initialize:function(){
    this.credit_source = this.element;
    this.credit_source.down('a.button').observeExclusively('click', this.addSource.bind(this));
    this.sources = this.credit_source.down(".sources");
    this.template = this.sources.down('.template').remove().innerHTML;
    this.upload = this.credit_source.up('.upload');
    this.upload.down(".creditable .original_remix_content").observe("click", this.resetSources.bind(this));
    this.upload.down(".creditable .credited_remix_content").observe("click", function() { this.addSource(); this.credit_source.show(); }.bind(this));

    this.sources.select('.source').each(function(source){
      this.initializeEntry(source);
    }.bind(this));
  },

  addSource: function(){
    var template_str = this.template.replace(/NEW_RECORD/g, this._nextIndex());
    var entry = Element.fromHTML(template_str);
    this.initializeEntry(entry);
    this.sources.insert({ bottom: entry });
    Event.addBehavior.reload();
  },

  initializeEntry:function(entry){
    entry.down('a.remove').observeExclusively('click', this.removeEntry.bind(this, entry));
  },

  removeEntry:function(entry){
    entry.remove();
  },

  resetSources:function(){
    this.credit_source.hide();
    this.sources.update("");
  },

  _nextIndex: function(){
    if(this.index){ this.index--; }
    else { this.index = -1; }
    return this.index;
  }

});

Event.addBehavior({
  '.unified_uploader': UnifiedUploader,
  '.unified_uploader .collaborators': UnifiedUploader.Collaborator,
  '.unified_uploader .credit_source': UnifiedUploader.Credits,
  'body.musics .unified_uploader': function(){
    this.fire("unified_uploader:change-content", "music");
   },
  'body.videos .unified_uploader': function(){
    this.fire("unified_uploader:change-content", "video");
   },
  'body.games .unified_uploader': function(){
    this.fire("unified_uploader:change-content", "game");
  },
  'body.photos .unified_uploader': function(){
    this.fire("unified_uploader:change-content", "photo");
  },
  'body.designs .unified_uploader': function(){
    this.fire("unified_uploader:change-content", "design");
  },
  'body.generic_content .unified_uploader': function(){
    this.fire("unified_uploader:change-content", "generic-content");
  },
  'body.blog_posts .unified_uploader': function(){
    this.fire("unified_uploader:change-content", "blog_post");
  },
  'body.forums .unified_uploader': function(){
    this.fire("unified_uploader:change-content", "forum_post");
  },
  'body.topics .unified_uploader': function(){
    this.fire("unified_uploader:change-content", "forum_post");
  }
});
