
meltmedia.SmartForm =  Class.create(meltmedia.VisualComponent,{
  
  defaults: {
    METHOD: "POST",
    RESTORE_DEFAULT_ALL: false
  },
  
  initialize: function(_form, _type, config){
    this.form = _form; 
    this.type = _type;
    this.setVariables(config);
    this.initFormItems();
  },
  
  setVariables: function(cfg){
    this.restoreDefaultAll = this.getIfExist(cfg.restoreDefaultAll, this.defaults.RESTORE_DEFAULT_ALL);
    this.onSuccess = this.getIfExist(cfg.onSuccess, this.onSuccess);
    this.onFailure = this.getIfExist(cfg.onFailure, this.onFailure);
    this.onInvalid = this.getIfExist(cfg.onInvalid, this.onInvalid);
    this.method = this.getIFNotEmpty(this.form.method,this.defaults.METHOD);
    this.action = this.getIfExist(cfg.action, this.form.action);
  },
 
  initFormItems: function(){
    this.formItems = new Hash();
    var formElements = this.form.getElementsBySelector(".required");
    
    formElements.each(function(el){
      //somehow, blank() function in prototype doesn't work in IE so textarea needs to be cleared
      if(el.tagName.toLowerCase()=="textarea" && el.value.length<2) el.clear();
      
      var newItem = {
        dom: el
      }
        
      if (this.formItems.get(el.name) == undefined) {
        this.formItems.set(el.name,{els:[newItem]});
      }else{
        this.formItems.get(el.name).els.push(newItem);
      }
      
    }.bind(this));
   
  },
  
  validate: function(){
    this.isValid = true;
    
    this.formItems.each(function(fItem){
      var isValid=false;
      var items = fItem.value.els;
      
      if(items.length>1){
        items.each(function(el){
       
          if(el.dom.checked){
            isValid = true;
            throw $break;
          }
          
        })
      }else{
        var el = items[0].dom;     
        isValid = el.title != el.value && !el.value.blank();  
      }
      
      fItem.value.isValid = isValid;
      if(this.isValid)this.isValid = isValid;
    }.bind(this))
 
  },
  
  submit: function(ev){
    ev.stop();
    this.validate();
    
    if (this.isValid) {
      if(this.type=="ajax"){
        this.form.request({
          onSuccess: this.onSuccess,
          onFailure: this.onFailure
        });
      }else{
        this.form.submit();
      }
    }else{
      this.onInvalid(this.formItems);
    }
  },
  
  onSuccess: function(){
    //console.info('success');
  },
  
  onFailure: function(){
    //console.info('failure');
  },
  
  onInvalid: function(items){
   //console.info(items);
  }
  
});

