// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var FileUploader = Class.create({
  
  initialize: function(form, slots,max_slots) {
    this.slots = slots;
    this.form = form;
    this.max_slots = max_slots;
    this.slot_counter = 0;
  },
  
  //add a new file slot
  add_slot : function(e){
    if(this.maxed_out() == false)
    {
      var parent = new Element("div", {'class': "new_file file_field"})
      
      var slot = this.slot();

      parent.appendChild(slot)
      parent.appendChild(this.remove_button(slot))
      this.slots.appendChild(parent)      
    } else {
      alert("Sorry, you can not add any more files.")
    }
    return false;
  },
  
  slot_count : function(){
    return $$(".file_field").length
  },
  
  check_buttons : function(){
    if((this.slot_count() >= this.max_slots) == true) {
      this.buttons.add_file.src = "/images/assets/add_file_disabled.png"
    }
    else
    {
      this.buttons.add_file.src = "/images/assets/add_file.png"
    }
    if($$(".new_file").length >= 1)
    {
      this.buttons.upload.src = "/images/assets/upload.png"
    }
    else
    {
      this.buttons.upload.src = "/images/assets/upload_disabled.png"
    }
  },
  
  slot : function(){
    var slot_id = this.slot_counter++
    var slot = new Element("input", {
                    'class': "new_file file_field",
                    'id':"assets_file_slot_"+slot_id+"_inputfile",
                    'name':"assets[file_slot_"+slot_id+"][inputfile]",
                    'type':'file',
                    'class':'input'})
    
    return slot;
  },
  
  buttons: function(buttons){
    var handler = this
    this.buttons = buttons
    this.buttons.add_file.observe('click', function(){handler.add_slot()})
    this.buttons.upload.observe('click',   function(){handler.upload()})
    
    this.buttons.add_file.observe('click', function(){handler.check_buttons()})
    this.buttons.upload.observe('click',   function(){handler.check_buttons()})
    this.check_buttons();
    
  },
  
  remove_slot : function(slot){    
    slot.up().remove()
    this.check_buttons();
    return false;
  },
  
  //Returns true if all the slots are used
  maxed_out : function()
  {
    return(this.slot_count() >= this.max_slots)
  },
  
  remove_button :function(slot){
    var handler = this;
    var button = new Element("b", {
            'text': "Remove",
            'class': 'remove button'});
    button.update("Remove")
    button.observe('click', function(){handler.remove_slot(slot)})
    return button
  },
  
  upload : function(){    
    this.remove_slot          = function(){};
    this.add_slot             = function(){};
    this.buttons.add_file.src = "/images/assets/add_file_disabled.png"
    this.buttons.upload.src   = "/images/assets/upload_disabled.png"
    this.form.submit();    
  }
})
