Event.addBehavior.reassignAfterAjax = true;

document.observe('dom:loaded', function(){
  var highlightAnchor = function() {
    if (document.location.hash == "") { return; }
    var anchorName = document.location.hash.slice(1);
    var anchor = $$("a[name='"+anchorName+"']")[0];
    if (anchor) { new Effect.Pulsate(anchor.parentNode, {pulses: 3}); }
  };
  highlightAnchor();
});

Event.addBehavior({
  '#content_remix:click':function(){
    $('content_sources').show();
  },

  '#content_original:click': function(){
    $('creditable_sources').hide();
  },
  
  'select[data-link=true]:change': function(e){
    window.location.href = this.value;
  }
});

var Application = {};

Application = {
  /* Example usage:
    new Ajax.Request(url, {
      asynchronous:true, evalScripts:true, method:'put',
      parameters: 'authenticity_token=' +
        encodeURIComponent(Application.authenticityToken())
    });

    Credit: Dan Morrison @ CollectiveIdea (Brandon Keepers as evangelist)
  */
  authenticityToken: function() {
    return $('authenticity-token').content;
  },

  authenticityTokenParameter: function(){
   return 'authenticity_token=' + encodeURIComponent(Application.authenticityToken());
  },
  
  iframeLoaded: function(json, iframe){
    Application.MessageBus.fire('iframeLoaded', json.evalJSON(), iframe);
  },
  
  addSpinnerTo: function(element, options){
    options = Object.extend({}, options);
    var spinner = Element.fromHTML("<img class=\"spinner\">");
    var offsets = { 
      setHeight: false, 
      setWidth: false
    };
    $$("body")[0].insert({bottom: spinner});

    // 
    if(element.getAttribute("type") == "text"){
      offsets["offsetTop"] = 3;
      offsets["offsetLeft"] = element.offsetWidth - spinner.offsetWidth;
    }
    
    if(options["position"] == "center"){
      offsets["offsetLeft"] = Math.abs(element.offsetWidth - spinner.offsetWidth) / 2;
      offsets["offsetTop"] = Math.abs(element.offsetHeight - spinner.offsetHeight) / 2;
    }
    
    spinner.clonePosition(element, offsets);
    return spinner
  }
};

Application.MessageBus = (function(){
  var registrar = { 
    callbacks: [],
    
    register: function(name, source, func){
      this.callbacks.push({ name: name, func: func, source: source });
    },
    
    registerForOneTimeEvent: function(name, source, func){
      this.register(name, source, func.wrap(function(proceed){
        proceed.apply(this, Array.prototype.slice.call(arguments, 1));
        this.unregister(name, source);
      }.bind(this)));
    },
    
    fire: function(name){
      var args = Array.prototype.slice.call(arguments, 1);
      this.callbacks.each(function(callback){ 
        if(callback.name == name) callback.func.apply(this, args);
      });
    },
    
    unregister: function(name, source){
      this.callbacks = this.callbacks.select(function(callback){
        return !(callback.name == name && callback.source == source);
      });
    }
  };
  return registrar;
})();

Application.CloseFlashMessage = Behavior.create({
  onclick: function(event) {
    event.stop();
    this.element.up('.flash').fade(1000);
  }
});

Application.CloseAnnouncement = Behavior.create({
  initialize: function() {
    if(this.announcementHidden(this.element.up(".announcement").getAttribute("data-id"))) {
      this.element.up(".announcement").hide();
    }
  },

  announcementHidden: function(id) {
    return this.announcementsHidden().include(id);
  },

  hideAnnouncement: function(id) {
    var announcements_hidden  = this.announcementsHidden();
    announcements_hidden.push(id);
    Cookie.set("announcements_hidden", announcements_hidden.toJSON(), 365);
  },

  announcementsHidden: function() {
    if(Cookie.get("announcements_hidden")) {
      return Cookie.get("announcements_hidden").evalJSON();
    } else {
      return [];
    }
  },

  onclick: function(event) { event.stop();
    this.hideAnnouncement(this.element.up(".announcement").getAttribute("data-id"));
  }
});

Application.UnpublishMedia = Behavior.create({
  onclick: function(event) {
    event.stop();
    
    if(confirm("Are you sure you want to unpublish this content?")){
      this.spinner = $$('body .spinner').first();
      this.icon = this.element.down(".icon");
      this.icon.setOpacity(0.1);
      this.spinner.clonePosition(this.icon);
      this.spinner.show();

      new Ajax.Request(this.element.getAttribute('href'), {
        method: 'put',
        requestHeaders: { 'Accept': 'application/json' },
        parameters: Application.authenticityTokenParameter(),
        onSuccess: function(response){
          window.location.href = response.responseJSON.redirectTo;
        }
      });
    }
  }
});

Event.addBehavior({
  'p.flash .close a': Application.CloseFlashMessage,
  'p.announcement .close a': Application.CloseAnnouncement,
  'a.button.unpublish': Application.UnpublishMedia
});

Application.NonGetBasedLink = Behavior.create({
  initialize: function() {
    this.link = this.element;
    var generic = this.link.getAttribute("data-generic");

    // only handle update links that are generic
    if(generic != "no"){
      this.confirm_message = this.link.getAttribute("data-confirm");
      this.form = this.setupForm();
      this.link.observe("click", this.submitForm.bind(this));
    }
  },

  setupForm: function() {
    var form = document.createElement('form'); 
    form.style.display = 'none'; 
    form.method = 'POST'; 
    form.action = this.link.getAttribute("href");
    
    form.appendChild(this.setupInput());
    if(Application.authenticityToken()) { form.appendChild(this.setupAuthenticityToken()); };
    
    this.link.parentNode.appendChild(form);     
    return form;
  },
  
  setupInput: function() {
    var method = document.createElement('input'); 
    method.setAttribute('type', 'hidden'); 
    method.setAttribute('name', '_method'); 
    method.setAttribute('value', this.http_method);
    return method;
  },
  
  setupAuthenticityToken: function() {
    var authenticity_token = document.createElement('input'); 
    authenticity_token.setAttribute('type', 'hidden'); 
    authenticity_token.setAttribute('name', 'authenticity_token'); 
    authenticity_token.setAttribute('value', Application.authenticityToken());
    return authenticity_token;
  },
  
  submitForm: function(event) {
    event.stop();
    
    if(!this.confirm_message) {
      this.form.submit();
    } else if(confirm(this.confirm_message)) {
      this.form.submit();
    }    
  }
});

Application.DeleteLink = Behavior.create(Application.NonGetBasedLink, {
  initialize: function($super){
    this.http_method = "delete";
    $super();
  }
});

Application.PostLink = Behavior.create(Application.NonGetBasedLink, {
  initialize: function($super){
    this.http_method = "post";
    $super();
  }
});

Application.PutLink = Behavior.create(Application.NonGetBasedLink, {
  initialize: function($super){
    this.http_method = "put";
    $super();
  }
});


Event.addBehavior({
  "a[data-method=delete]:not([data-remote=true])": Application.DeleteLink,
  "a[data-method=post]:not([data-remote=true])": Application.PostLink,
  "a[data-method=put]:not([data-remote=true])": Application.PutLink
});

