/**
* Cad Class
* Class para distribuição das funções das telas de cadastr o
* @author Fernando Andreacci
* OS 5321 
*/         

//Inicia a classe
var Cad = Class.create();  
   
Cad.prototype = {
       
 //Construtor
 initialize: function(setup){
     this.config  = setup;
     this.lastUpdateId = null;
     
     this.urlModel = this.config.url + '/system/framework/html/Form/cad/model.php';
     this.urlImg   = this.config.url + '/conf/images/spinner.gif';
     
     this.pg_number = 0;     
     
 },
 
 /**
 * Update
 *
 */      
 Update: function(id,ds_button) {
     
     this.Start();
     this.lastUpdateId = id;      
     
     Form.reset(this.config.form.id);
     
     var pars = 'table='+this.config.table+'&op=update&id='+id+'&nocache=' + cacheBuster();
     new Ajax.Request(
         this.urlModel,
         {
           method: 'get',
           parameters: pars,
           onComplete: this.AfterUpdate.bind(this),
           onSuccess:  function(t) {
                         t.responseText.evalScripts();                                                                           
                      }                                  
         }                  
     );    
     //[Robertson][19/04/2007][OS 5876-068][Inclír parâmetro para adicionar a descrição do botão].
   
   /**
          * @author: Juvenal Marcos Batista
          * @date: 07/10/2008
          * @OS:  6368-167
          * @Descrição: Alteração na descrição do botão, mudou de Editar para Gravar
          * @Inspecionado por: Edina de Souza Inacio
          * @Data de Inspeção: 07/10/2008
          */
   
	 if(!ds_button){
	     ds_button = 'Gravar';    	
	 }	 
     
	 $(this.config.table+'Save').value = ds_button;
     
 },
               
 Delete: function(id) {
     this.Start();
     
     var pars = 'table='+this.config.table+'&op=delete&id='+id+'&nocache' + cacheBuster();
     
     if(this.config.beforeDelete) {
        pars += '&beforeDelete='+this.config.beforeDelete;
     }      
     new Ajax.Request(
            this.urlModel,
            {
              method: 'get',
              parameters: pars,
              onComplete: this.Stop.bind(this),
              onSuccess: function(e) {
                             e.responseText.evalScripts();                             
                        }
            }
     );           
    
	Form.reset(this.config.form.id);
    $(this.config.table+'Save').value = 'Gravar';                  
    
 },
       
 Insert: function() {
       
     this.Start();

     var pars = '&table='+this.config.table+'&nocache=' + cacheBuster()+ '&op=insert&'+
     '&pk[Filter] = ' + this.config.pk.filter +  '&pk[User] = ' +this.config.pk.user + '&pk[Guni] = ' +
     this.config.pk.guni + '&pk[Size]='+this.config.pk.size;
     
     if(this.config.beforeInsert)
        pars += '&beforeInsert='+this.config.beforeInsert;
     
     if(this.config.beforeUpdate)        
        pars += '&beforeUpdate='+this.config.beforeUpdate;     
        
     if(this.config.afterInsert_callback) 
       pars += '&afterInsert_callback=' + this.config.afterInsert_callback;

     if(this.config.beforeInsert){
		 var After = window.location.reload();
	 }else{  
	     var After = this.AfterInsert.bind(this);
	 } 

     new Ajax.Request(
            this.urlModel,
            {
              method: 'get',
              parameters: cadFormSerialize(this.config.form.id) + pars ,
              onComplete: After,
              onSuccess: function (f) { 
                          f.responseText.evalScripts();                          
              } 
           }
     );
     
     Form.reset(this.config.form.id);
     //para executar insert depois de um update necessita remover o valor de primarykey.
     $('fields['+this.config.table+'][PRIMARYKEY]').value = '';
     
     $(this.config.table+'Save').value = 'Gravar';     
  },    
       
  Getall: function(pg_number) {            
    
	this.Start();    
   
    this.pg_number = pg_number;
              
     var url  = this.urlModel + '?table=' + this.config.table + '&op=getall' + 
                toUrl('ShowFields',this.config.list.ConfigFields.fields) +                 
                toUrl('ListNames',this.config.list.ConfigFields.captions) +
                toUrl('ListSizes',this.config.list.ConfigFields.sizes) + 
                '&pg_number=' + pg_number +
                '&nocache=' + cacheBuster();
     
     //[Fernando][os???][25/07/2007]
     if(this.config.list.ConfigFields.hideButtons) {
	   url += toUrl('HideButtons',this.config.list.ConfigFields.hideButtons);
	 }
	 
                
     //Se existir números de registro por página
     if(this.config.list.ConfigFields.registers)
         url += '&registers=' + this.config.list.ConfigFields.registers;
		                       
      
     //Se existir uma query
     if(this.config.list.sql)
         url += '&sql=' +  this.config.list.sql;                   


     new Ajax.Updater(this.config.list.id, url,{asynchronous:true,onComplete: this.Stop.bind(this), evalScripts: true } );

  },
      
  Start: function() {
       Form.disable(this.config.form.id);
       $('Wait'+this.config.table).innerHTML = 'Aguarde...  <img src='+ this.urlImg+ '></img>';
  },
      
  Stop: function() {
       Form.enable(this.config.form.id);            
       $('Wait'+this.config.table).innerHTML = '';
  },
  
  AfterUpdate: function(id) {    
    
    if(this.config.AfterUpdate)
         this.config.AfterUpdate(this.lastUpdateId);
     
     //mostra o elemento se estiver vazio
     Element.show('formbody' + this.config.form.id);
     this.Stop();    
  }, 
  
  AfterInsert: function(id){
    
    if(this.config.AfterInsert)
         this.config.AfterInsert();

     this.pg_number = 0;     
	 this.Getall(this.pg_number);    	 	   
  }  
                   
  
};  
  
function toUrl(key,option) {

  if(!option) 
    return;

  
  var url = ''; 
  for(var i =0; i< option.length; i++) 
  {
    url +=  '&'+key + '[]=' + option[i];        
  }   

  return url;
}
//[Fernando][5978-025][18/06/2007]
function cadFormSerialize(id) {
    var elements = Form.getElements($(id));
    var queryComponents = new Array();
    for (var i = 0; i < elements.length; i++) {
      if(elements[i].id.substring(0,5) != 'GHOST') {
	    var queryComponent = Form.Element.serialize(elements[i]);
        if (queryComponent)
          queryComponents.push(queryComponent);
      }
    }
    return queryComponents.join('&');
}

function cacheBuster() {

  var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
  var randomstring = '';
        
  for (var i=0; i<20; i++) {
     	var rnum = Math.floor(Math.random() * chars.length);
  		randomstring += chars.substring(rnum,rnum+1);
  }        	
  return randomstring + new Date().getTime();    
}