// Medios
var aaa='';
var noRepetidos='';
var btn;
var upload_dialog;
var ulDialog;
var filtroUploads='';
var textoBotonMedios='Agregar archivo al Cat&aacute;logo de Medios';
var gSubniveles='../../../../';

function alertaxx(){
	if(!ulDialog){
		    ulDialog = new Ext.Window({
				title: 'Administracion de Archivos',
		    	id: 'ventana-file-upload',
				width:900,
				y:0,
				heigth:330,
				modal: true,
				closeAction: 'hide',
				border: true,
				collapsible:true,
				collapsed:false,
				html:'<table><tr><td colspan="2"><div id="barraBotones"></div></td></tr><tr><td bgcolor="red" valign="top" style="overflow-y:auto;max-height:330px; background:#ff9900; height:330px;"><div id="treeX" style="overflow-y:auto;max-height:330px; background:#ff9900; height:330px;" ></div></td><td><div id="gridFiles"></div></td></tr></table>'
				
				});
			}
			ulDialog.show();			
			barraBotones.render('barraBotones');
			gridFiles.render('gridFiles');
			tree.render('treeX');

	}

///////////////////// Librerķas
Ext.namespace('Ext.ux.Utils');



/**
 * This class implements event queue behaviour.
 *
 * @class Ext.ux.Utils.EventQueue
 * @param function  handler  Event handler.
 * @param object    scope    Handler scope.
 */
Ext.ux.Utils.EventQueue = function(handler, scope)
{
  if (!handler) {
    throw 'Handler requerido.';
  }
  this.handler = handler;
  this.scope = scope || window;
  this.queue = [];
  this.is_processing = false;
  
  /**
   * Posts event into the queue.
   * 
   * @access public
   * @param mixed event Event identificator.
   * @param mixed data  Event data.
   */
  this.postEvent = function(event, data)
  {
    data = data || null;
    this.queue.push({event: event, data: data});
    if (!this.is_processing) {
      this.process();
    }
  }
  
  this.flushEventQueue = function()
  {
    this.queue = [];
  },
  
  /**
   * @access private
   */
  this.process = function()
  {
    while (this.queue.length > 0) {
      this.is_processing = true;
      var event_data = this.queue.shift();
      this.handler.call(this.scope, event_data.event, event_data.data);
    }
    this.is_processing = false;
  }
}

/**
 * This class implements Mili's finite state automata behaviour.
 *  
 *  Transition / output table format:
 *  {
 *    'state_1' : {
 *      'event_1' : [
 *        {
 *          p|predicate: function,    // Transition predicate, optional, default to true.
 *                                    // If array then conjunction will be applyed to the operands.
 *                                    // Predicate signature is (data, event, this).
 *          a|action: function|array, // Transition action, optional, default to Ext.emptyFn.
 *                                    // If array then methods will be called sequentially.
 *                                    // Action signature is (data, event, this).
 *          s|state: 'state_x',       // New state - transition destination, optional, default to 
 *                                    // current state.
 *          scope: object             // Predicate and action scope, optional, default to 
 *                                    // trans_table_scope or window.
 *        }
 *      ]
 *    },
 *
 *    'state_2' : {
 *      ...
 *    }
 *    ...
 *  }
 *
 *  @param  mixed initial_state Initial state.
 *  @param  object trans_table Transition / output table.
 *  @param  trans_table_scope Transition / output table's methods scope.
 */
Ext.ux.Utils.FSA = function(initial_state, trans_table, trans_table_scope)
{
  this.current_state = initial_state;
  this.trans_table = trans_table || {};
  this.trans_table_scope = trans_table_scope || window;
  Ext.ux.Utils.FSA.superclass.constructor.call(this, this.processEvent, this);
}

Ext.extend(Ext.ux.Utils.FSA, Ext.ux.Utils.EventQueue, {

  current_state : null,
  trans_table : null,  
  trans_table_scope : null,
  
  /**
   * Returns current state
   * 
   * @access public
   * @return mixed Current state.
   */
  state : function()
  {
    return this.current_state;
  },
  
  /**
   * @access public
   */
  processEvent : function(event, data)
  {
    var transitions = this.currentStateEventTransitions(event);
    if (!transitions) {
      throw "State '" + this.current_state + "' has no transition for event '" + event + "'.";
    }
    for (var i = 0, len = transitions.length; i < len; i++) {
      var transition = transitions[i];

      var predicate = transition.predicate || transition.p || true;
      var action = transition.action || transition.a || Ext.emptyFn;
      var new_state = transition.state || transition.s || this.current_state;
      var scope = transition.scope || this.trans_table_scope;
      
      if (this.computePredicate(predicate, scope, data, event)) {
        this.callAction(action, scope, data, event);
        this.current_state = new_state; 
        return;
      }
    }
    
    throw "State '" + this.current_state + "' has no transition for event '" + event + "' in current context";
  },
  
  /**
   * @access private
   */
  currentStateEventTransitions : function(event)
  {
    return this.trans_table[this.current_state] ? 
      this.trans_table[this.current_state][event] || false
      :
      false;
  },
  
  /**
   * @access private
   */
  computePredicate : function(predicate, scope, data, event)
  {
    var result = false; 
    
    switch (Ext.type(predicate)) {
     case 'function':
       result = predicate.call(scope, data, event, this);
       break;
     case 'array':
       result = true;
       for (var i = 0, len = predicate.length; result && (i < len); i++) {
         if (Ext.type(predicate[i]) == 'function') {
           result = predicate[i].call(scope, data, event, this);
         }
         else {
           throw [
             'Predicate: ',
             predicate[i],
             ' is not callable in "',
             this.current_state,
             '" state for event "',
             event
           ].join('');
         }
       }
       break;
     case 'boolean':
       result = predicate;
       break;
     default:
       throw [
         'Predicate: ',
         predicate,
         ' is not callable in "',
         this.current_state,
         '" state for event "',
         event
       ].join('');
    }
    return result;
  },
  
  /**
   * @access private
   */
  callAction : function(action, scope, data, event)
  {
    switch (Ext.type(action)) {
       case 'array':
       for (var i = 0, len = action.length; i < len; i++) {
         if (Ext.type(action[i]) == 'function') {
           action[i].call(scope, data, event, this);
         }
         else {
           throw [
             'Action: ',
             action[i],
             ' is not callable in "',
             this.current_state,
             '" state for event "',
             event
           ].join('');
         }
       }
         break;
     case 'function':
       action.call(scope, data, event, this);
       break;
     default:
       throw [
         'Action: ',
         action,
         ' is not callable in "',
         this.current_state,
         '" state for event "',
         event
       ].join('');
    }
  }
});

// ---------------------------------------------------------------------------------------------- //

/**
 * Ext.ux.UploadDialog namespace.
 */
Ext.namespace('Ext.ux.UploadDialog');

/**
 * File upload browse button.
 *
 * @class Ext.ux.UploadDialog.BrowseButton
 */ 
Ext.ux.UploadDialog.BrowseButton = Ext.extend(Ext.Button, 
{
  input_name : 'file',
  
  input_file : null,
  
  original_handler : null,
  
  original_scope : null,
  
  /**
   * @access private
   */
  initComponent : function()
  {
    Ext.ux.UploadDialog.BrowseButton.superclass.initComponent.call(this);
    this.original_handler = this.handler || null;
    this.original_scope = this.scope || window;
    this.handler = null;
    this.scope = null;
  },
  
  /**
   * @access private
   */
  onRender : function(ct, position)
  {
    Ext.ux.UploadDialog.BrowseButton.superclass.onRender.call(this, ct, position);
    this.createInputFile();
  },
  
  /**
   * @access private
   */
  createInputFile : function()
  {
    var button_container = this.el.child('.x-btn-center');
    button_container.position('relative');
    this.input_file = Ext.DomHelper.append(
      button_container, 
      {
        tag: 'input',
        type: 'file',
        size: 1,
        name: this.input_name || Ext.id(this.el),
        style: 'position: absolute; display: block; border: none; cursor: pointer'
      },
      true
    );
    
    var button_box = button_container.getBox();
    this.input_file.setStyle('font-size', (button_box.width * 0.5) + 'px');

    var input_box = this.input_file.getBox();
    var adj = {x: 3, y: 3}
    if (Ext.isIE) {
      adj = {x: 0, y: 3}
    }

    
    this.input_file.setLeft(button_box.width - input_box.width + adj.x + 'px');
    this.input_file.setTop(button_box.height - input_box.height + adj.y + 'px');
    this.input_file.setOpacity(0.0);
        
    if (this.handleMouseEvents) {
      this.input_file.on('mouseover', this.onMouseOver, this);
        this.input_file.on('mousedown', this.onMouseDown, this);
    }
    
    if(this.tooltip){
      if(typeof this.tooltip == 'object'){
        Ext.QuickTips.register(Ext.apply({target: this.input_file}, this.tooltip));
      } 
      else {
        this.input_file.dom[this.tooltipType] = this.tooltip;
        }
      }
    
    this.input_file.on('change', this.onInputFileChange, this);
    this.input_file.on('click', function(e) { e.stopPropagation(); }); 
  },
  
  /**
   * @access public
   */
  detachInputFile : function(no_create)
  {
    var result = this.input_file;
    
    no_create = no_create || false;
    
    if (typeof this.tooltip == 'object') {
      Ext.QuickTips.unregister(this.input_file);
    }
    else {
      this.input_file.dom[this.tooltipType] = null;
    }
    this.input_file.removeAllListeners();
    this.input_file = null;
    
    if (!no_create) {
      this.createInputFile();
    }
    return result;
  },
  
  /**
   * @access public
   */
  getInputFile : function()
  {
    return this.input_file;
  },
  
  /**
   * @access public
   */
  disable : function()
  {
    Ext.ux.UploadDialog.BrowseButton.superclass.disable.call(this);  
    this.input_file.dom.disabled = true;
  },
  
  /**
   * @access public
   */
  enable : function()
  {
    Ext.ux.UploadDialog.BrowseButton.superclass.enable.call(this);
    this.input_file.dom.disabled = false;
  },
  
  /**
   * @access public
   */
  destroy : function()
  {
    var input_file = this.detachInputFile(true);
    input_file.remove();
    input_file = null;
    Ext.ux.UploadDialog.BrowseButton.superclass.destroy.call(this);      
  },
  
  /**
   * @access private
   */
  onInputFileChange : function()
  {
    if (this.original_handler) {
      this.original_handler.call(this.original_scope, this);
    }
  }  
});

/**
 * Toolbar file upload browse button.
 *
 * @class Ext.ux.UploadDialog.TBBrowseButton
 */
Ext.ux.UploadDialog.TBBrowseButton = Ext.extend(Ext.ux.UploadDialog.BrowseButton, 
{
  hideParent : true,

  onDestroy : function()
  {
    Ext.ux.UploadDialog.TBBrowseButton.superclass.onDestroy.call(this);
    if(this.container) {
      this.container.remove();
      }
  }
});

/**
 * Record type for dialogs grid.
 *
 * @class Ext.ux.UploadDialog.FileRecord 
 */
Ext.ux.UploadDialog.FileRecord = Ext.data.Record.create([
  {name: 'filename'},
  {name: 'state', type: 'int'},
  {name: 'note'},
  {name: 'input_element'},
  {name: 'path'}  
]);

Ext.ux.UploadDialog.FileRecord.STATE_QUEUE = 0;
Ext.ux.UploadDialog.FileRecord.STATE_FINISHED = 1;
Ext.ux.UploadDialog.FileRecord.STATE_FAILED = 2;
Ext.ux.UploadDialog.FileRecord.STATE_PROCESSING = 3;

/**
 * Dialog class.
 *
 * @class Ext.ux.UploadDialog.Dialog
 */
Ext.ux.UploadDialog.Dialog = function(config)
{
  var default_config = {
    border: false,
    width: 450,
    height: 300,
    minWidth: 450,
    minHeight: 300,
    plain: true,
    constrainHeader: true,
    draggable: true,
    closable: true,
    maximizable: false,
    minimizable: false,
    resizable: true,
    autoDestroy: true,
    closeAction: 'hide',
    title: this.i18n.title,
    cls: 'ext-ux-uploaddialog-dialog',
    // --------
    url: '',
    base_params: {},
    permitted_extensions: [],
    reset_on_hide: true,
    allow_close_on_upload: false,
    upload_autostart: false
  }
  config = Ext.applyIf(config || {}, default_config);
  config.layout = 'absolute';
  
  Ext.ux.UploadDialog.Dialog.superclass.constructor.call(this, config);
}

Ext.extend(Ext.ux.UploadDialog.Dialog, Ext.Window, {

  fsa : null,
  
  state_tpl : null,
  
  form : null,
  
  grid_panel : null,
  
  progress_bar : null,
  
  is_uploading : false,
  
  initial_queued_count : 0,
  
  upload_frame : null,
  
  /**
   * @access private
   */
  //--------------------------------------------------------------------------------------------- //
  initComponent : function()
  {
    Ext.ux.UploadDialog.Dialog.superclass.initComponent.call(this);
    
    // Setting automata protocol
    var tt = {
      // --------------
      'created' : {
      // --------------
        'window-render' : [
          {
            action: [this.createForm, this.createProgressBar, this.createGrid],
            state: 'rendering'
          }
        ],
        'destroy' : [
          {
            action: this.flushEventQueue,
            state: 'destroyed'
          }
        ]
      },
      // --------------
      'rendering' : {
      // --------------
        'grid-render' : [
          {
            action: [this.fillToolbar, this.updateToolbar],
            state: 'ready'
          }
        ],
        'destroy' : [
          {
            action: this.flushEventQueue,
            state: 'destroyed'
          }
        ]
      },
      // --------------
      'ready' : {
      // --------------
        'file-selected' : [
          {
            predicate: [this.fireFileTestEvent, this.isPermittedFile],
            action: this.addFileToUploadQueue,
            state: 'adding-file'
          },
          {
            // If file is not permitted then do nothing.
          }
        ],
        'grid-selection-change' : [
          {
            action: this.updateToolbar
          }
        ],
        'remove-files' : [
          {
            action: [this.removeFiles, this.fireFileRemoveEvent]
          }
        ],
        'reset-queue' : [
          {
            action: [this.resetQueue, this.fireResetQueueEvent]
          }
        ],
        'start-upload' : [
          {
            predicate: this.hasUnuploadedFiles,
            action: [
              this.setUploadingFlag, this.saveInitialQueuedCount, this.updateToolbar, 
              this.updateProgressBar, this.prepareNextUploadTask, this.fireUploadStartEvent
            ],
            state: 'uploading'
          },
          {
            // Has nothing to upload, do nothing.
          }
        ],
        'stop-upload' : [
          {
            // We are not uploading, do nothing. Can be posted by user only at this state. 
          }
        ],
        'hide' : [
          {
            predicate: [this.isNotEmptyQueue, this.getResetOnHide],
            action: [this.resetQueue, this.fireResetQueueEvent]
          },
          {
            // Do nothing
          }
        ],
        'destroy' : [
          {
            action: this.flushEventQueue,
            state: 'destroyed'
          }
        ]
      },
      // --------------
      'adding-file' : {
      // --------------
        'file-added' : [
          {
            predicate: this.isUploading,
            action: [this.incInitialQueuedCount, this.updateProgressBar, this.fireFileAddEvent],
            state: 'uploading' 
          },
          {
            predicate: this.getUploadAutostart,
            action: [this.startUpload, this.fireFileAddEvent],
            state: 'ready'
          },
          {
            action: [this.updateToolbar, this.fireFileAddEvent],
            state: 'ready'
          }
        ]
      },
      // --------------
      'uploading' : {
      // --------------
        'file-selected' : [
          {
            predicate: [this.fireFileTestEvent, this.isPermittedFile],
            action: this.addFileToUploadQueue,
            state: 'adding-file'
          },
          {
            // If file is not permitted then do nothing.
          }
        ],
        'grid-selection-change' : [
          {
            // Do nothing.
          }
        ],
        'start-upload' : [
          {
            // Can be posted only by user in this state. 
          }
        ],
        'stop-upload' : [
          {
            predicate: this.hasUnuploadedFiles,
            action: [
              this.resetUploadingFlag, this.abortUpload, this.updateToolbar, 
              this.updateProgressBar, this.fireUploadStopEvent
            ],
            state: 'ready'
          },
          {
            action: [
              this.resetUploadingFlag, this.abortUpload, this.updateToolbar, 
              this.updateProgressBar, this.fireUploadStopEvent, this.fireUploadCompleteEvent
            ],
            state: 'ready'
          }
        ],
        'file-upload-start' : [
          {
            action: [this.uploadFile, this.findUploadFrame, this.fireFileUploadStartEvent]
          }
        ],
        'file-upload-success' : [
          {
            predicate: this.hasUnuploadedFiles,
            action: [
              this.resetUploadFrame, this.updateRecordState, this.updateProgressBar, 
              this.prepareNextUploadTask, this.fireUploadSuccessEvent
            ]
          },
          {
            action: [
              this.resetUploadFrame, this.resetUploadingFlag, this.updateRecordState, 
              this.updateToolbar, this.updateProgressBar, this.fireUploadSuccessEvent, 
              this.fireUploadCompleteEvent
            ],
            state: 'ready'
          }
        ],
        'file-upload-error' : [
          {
            predicate: this.hasUnuploadedFiles,
            action: [
              this.resetUploadFrame, this.updateRecordState, this.updateProgressBar, 
              this.prepareNextUploadTask, this.fireUploadErrorEvent
            ]
          },
          {
            action: [
              this.resetUploadFrame, this.resetUploadingFlag, this.updateRecordState, 
              this.updateToolbar, this.updateProgressBar, this.fireUploadErrorEvent, 
              this.fireUploadCompleteEvent
            ],
            state: 'ready'
          }
        ],
        'file-upload-failed' : [
          {
            predicate: this.hasUnuploadedFiles,
            action: [
              this.resetUploadFrame, this.updateRecordState, this.updateProgressBar, 
              this.prepareNextUploadTask, this.fireUploadFailedEvent
            ]
          },
          {
            action: [
              this.resetUploadFrame, this.resetUploadingFlag, this.updateRecordState, 
              this.updateToolbar, this.updateProgressBar, this.fireUploadFailedEvent, 
              this.fireUploadCompleteEvent
            ],
            state: 'ready'
          }
        ],
        'hide' : [
          {
            predicate: this.getResetOnHide,
            action: [this.stopUpload, this.repostHide]
          },
          {
            // Do nothing.
          }
        ],
        'destroy' : [
          {
            predicate: this.hasUnuploadedFiles,
            action: [
              this.resetUploadingFlag, this.abortUpload,
              this.fireUploadStopEvent, this.flushEventQueue
            ],
            state: 'destroyed'
          },
          {
            action: [
              this.resetUploadingFlag, this.abortUpload,
              this.fireUploadStopEvent, this.fireUploadCompleteEvent, this.flushEventQueue
            ], 
            state: 'destroyed'
          }
        ]
      },
      // --------------
      'destroyed' : {
      // --------------
      }
    }
    this.fsa = new Ext.ux.Utils.FSA('created', tt, this);
    
    // Registering dialog events.
    this.addEvents({
      'filetest': true,
      'fileadd' : true,
      'fileremove' : true,
      'resetqueue' : true,
      'uploadsuccess' : true,
      'uploaderror' : true,
      'uploadfailed' : true,
      'uploadstart' : true,
      'uploadstop' : true,
      'uploadcomplete' : true,
      'fileuploadstart' : true
    });
    
    // Attaching to window events.
    this.on('render', this.onWindowRender, this);
    this.on('beforehide', this.onWindowBeforeHide, this);
    this.on('hide', this.onWindowHide, this);
    this.on('destroy', this.onWindowDestroy, this);
    
    // Compiling state template.
    this.state_tpl = new Ext.Template(
      "<div class='ext-ux-uploaddialog-state ext-ux-uploaddialog-state-{state}'>&#160;</div>"
    ).compile();
  },
  
  createForm : function()
  {
    this.form = Ext.DomHelper.append(this.body, {
      tag: 'form',
      method: 'post',
      action: this.url,
      style: 'position: absolute; left: -100px; top: -100px; width: 100px; height: 100px'
    });
  },
  
  createProgressBar : function()
  {
    this.progress_bar = this.add(
      new Ext.ProgressBar({
        x: 0,
        y: 0,
        anchor: '0',
        value: 0.0,
        text: this.i18n.progress_waiting_text
      })
    );
  },
  
  createGrid : function()
  {
    var store = new Ext.data.Store({
      proxy: new Ext.data.MemoryProxy([]),
      reader: new Ext.data.JsonReader({}, Ext.ux.UploadDialog.FileRecord),
      sortInfo: {field: 'state', direction: 'DESC'},
      pruneModifiedRecords: true
    });
    
    var cm = new Ext.grid.ColumnModel([
      {
        header: this.i18n.state_col_title,
        width: this.i18n.state_col_width,
        resizable: false,
        dataIndex: 'state',
        sortable: true,
        renderer: this.renderStateCell.createDelegate(this)
      },
      {
        header: this.i18n.filename_col_title,
        width: this.i18n.filename_col_width,
        dataIndex: 'filename',
        sortable: true,
        renderer: this.renderFilenameCell.createDelegate(this)
      },
      {
        header: this.i18n.note_col_title,
        width: this.i18n.note_col_width, 
        dataIndex: 'note',
        sortable: true,
        renderer: this.renderNoteCell.createDelegate(this)
      }
    ]);
  
      this.grid_panel = new Ext.grid.GridPanel({
      ds: store,
      cm: cm,
    
      x: 0,
      y: 22,
      anchor: '0 -22',
      border: true,
      
        viewConfig: {
        autoFill: true,
          forceFit: true
        },
      
      bbar : new Ext.Toolbar()
    });
    this.grid_panel.on('render', this.onGridRender, this);
    
    this.add(this.grid_panel);
    
    this.grid_panel.getSelectionModel().on('selectionchange', this.onGridSelectionChange, this);
  },
  
  fillToolbar : function()
  {
    var tb = this.grid_panel.getBottomToolbar();
    tb.x_buttons = {}
    
    tb.x_buttons.add = tb.addItem(new Ext.ux.UploadDialog.TBBrowseButton({
      text: this.i18n.add_btn_text,
      tooltip: this.i18n.add_btn_tip,
      iconCls: 'ext-ux-uploaddialog-addbtn',
      handler: this.onAddButtonFileSelected,
      scope: this
    }));
    
    tb.x_buttons.remove = tb.addButton({
      text: this.i18n.remove_btn_text,
      tooltip: this.i18n.remove_btn_tip,
      iconCls: 'ext-ux-uploaddialog-removebtn',
      handler: this.onRemoveButtonClick,
      scope: this
    });
    
    tb.x_buttons.reset = tb.addButton({
      text: this.i18n.reset_btn_text,
      tooltip: this.i18n.reset_btn_tip,
      iconCls: 'ext-ux-uploaddialog-resetbtn',
      handler: this.onResetButtonClick,
      scope: this
    });
    
    tb.add('-');
    
    tb.x_buttons.upload = tb.addButton({
      text: this.i18n.upload_btn_start_text,
      tooltip: this.i18n.upload_btn_start_tip,
      iconCls: 'ext-ux-uploaddialog-uploadstartbtn',
      handler: this.onUploadButtonClick,
      scope: this
    });
    
    tb.add('-');
    
    tb.x_buttons.indicator = tb.addItem(
      new Ext.Toolbar.Item(
        Ext.DomHelper.append(tb.getEl(), {
          tag: 'div',
          cls: 'ext-ux-uploaddialog-indicator-stoped',
          html: '&#160'
        })
      )
    );
    
    tb.add('->');
    
    tb.x_buttons.close = tb.addButton({
      text: this.i18n.close_btn_text,
      tooltip: this.i18n.close_btn_tip,
      handler: this.onCloseButtonClick,
      scope: this
    });
  },
  
  renderStateCell : function(data, cell, record, row_index, column_index, store)
  {
    return this.state_tpl.apply({state: data});
  },
  
  renderFilenameCell : function(data, cell, record, row_index, column_index, store)
  {
    var view = this.grid_panel.getView();
    var f = function() {
      try {
        Ext.fly(
          view.getCell(row_index, column_index)
        ).child('.x-grid3-cell-inner').dom['qtip'] = data;
      }
      catch (e)
      {}
    }
    f.defer(1000);
    return data;
  },
  
  renderNoteCell : function(data, cell, record, row_index, column_index, store)
  {
    var view = this.grid_panel.getView();
    var f = function() {
      try {
        Ext.fly(
          view.getCell(row_index, column_index)
        ).child('.x-grid3-cell-inner').dom['qtip'] = data;
      }
      catch (e)
      {}
      }
    f.defer(1000);
    return data;
  },
  
  getFileExtension : function(filename)
  {
    var result = null;
    var parts = filename.split('.');
    if (parts.length > 1) {
      result = parts.pop();
    }
    return result;
  },
  
  isPermittedFileType : function(filename)
  {
    var result = true;
    if (this.permitted_extensions.length > 0) {
      result = this.permitted_extensions.indexOf(this.getFileExtension(filename)) != -1;
    }
    return result;
  },

  isPermittedFile : function(browse_btn)
  {
    var result = false;
    var filename = browse_btn.getInputFile().dom.value;
    
    if (this.isPermittedFileType(filename)) {
      result = true;
    }
    else {
      Ext.Msg.alert(
        this.i18n.error_msgbox_title, 
        String.format(
          this.i18n.err_file_type_not_permitted,
          filename,
          this.permitted_extensions.join(this.i18n.permitted_extensions_join_str)
        )
      );
      result = false;
    }
    
    return result;
  },
  
  fireFileTestEvent : function(browse_btn)
  {
    return this.fireEvent('filetest', this, browse_btn.getInputFile().dom.value) !== false;
  },
  
  addFileToUploadQueue : function(browse_btn)
  {
    var input_file = browse_btn.detachInputFile();
    
    input_file.appendTo(this.form);
    input_file.setStyle('width', '100px');
    input_file.dom.disabled = true;
    
    var store = this.grid_panel.getStore();
    store.add(
      new Ext.ux.UploadDialog.FileRecord({
          state: Ext.ux.UploadDialog.FileRecord.STATE_QUEUE,
          filename: input_file.dom.value,
          note: this.i18n.note_queued_to_upload,
          input_element: input_file
        })
      );
    this.fsa.postEvent('file-added', input_file.dom.value);
  },
  
  fireFileAddEvent : function(filename)
  {
    this.fireEvent('fileadd', this, filename);
  },
  
  updateProgressBar : function()
  {
    if (this.is_uploading) {
      var queued = this.getQueuedCount(true);
      var value = 1 - queued / this.initial_queued_count;
      this.progress_bar.updateProgress(
        value,
        String.format(
          this.i18n.progress_uploading_text, 
          this.initial_queued_count - queued,
          this.initial_queued_count
        )
      );
    }
    else {
      this.progress_bar.updateProgress(0, this.i18n.progress_waiting_text);
    }
  },
  
  updateToolbar : function()
  {
    var tb = this.grid_panel.getBottomToolbar();
    if (this.is_uploading) {
      tb.x_buttons.remove.disable();
      tb.x_buttons.reset.disable();
      tb.x_buttons.upload.enable();
      if (!this.getAllowCloseOnUpload()) {
        tb.x_buttons.close.disable();
      }
      Ext.fly(tb.x_buttons.indicator.getEl()).replaceClass(
        'ext-ux-uploaddialog-indicator-stoped',
        'ext-ux-uploaddialog-indicator-processing'
      );
      tb.x_buttons.upload.setIconClass('ext-ux-uploaddialog-uploadstopbtn');
      tb.x_buttons.upload.setText(this.i18n.upload_btn_stop_text);
      tb.x_buttons.upload.getEl()
        .child(tb.x_buttons.upload.buttonSelector)
        .dom[tb.x_buttons.upload.tooltipType] = this.i18n.upload_btn_stop_tip;
    }
    else {
      tb.x_buttons.remove.enable();
      tb.x_buttons.reset.enable();
      tb.x_buttons.close.enable();
      Ext.fly(tb.x_buttons.indicator.getEl()).replaceClass(
        'ext-ux-uploaddialog-indicator-processing',
        'ext-ux-uploaddialog-indicator-stoped'
      );
      tb.x_buttons.upload.setIconClass('ext-ux-uploaddialog-uploadstartbtn');
      tb.x_buttons.upload.setText(this.i18n.upload_btn_start_text);
      tb.x_buttons.upload.getEl()
        .child(tb.x_buttons.upload.buttonSelector)
        .dom[tb.x_buttons.upload.tooltipType] = this.i18n.upload_btn_start_tip;
      
      if (this.getQueuedCount() > 0) {
        tb.x_buttons.upload.enable();
      }
      else {
        tb.x_buttons.upload.disable();      
      }
      
      if (this.grid_panel.getSelectionModel().hasSelection()) {
        tb.x_buttons.remove.enable();
      }
      else {
        tb.x_buttons.remove.disable();
      }
      
      if (this.grid_panel.getStore().getCount() > 0) {
        tb.x_buttons.reset.enable();
      }
      else {
        tb.x_buttons.reset.disable();
      }
    }
  },
  
  saveInitialQueuedCount : function()
  {
    this.initial_queued_count = this.getQueuedCount();
  },
  
  incInitialQueuedCount : function()
  {
    this.initial_queued_count++;
  },
  
  setUploadingFlag : function()
  {
    this.is_uploading = true;
  }, 
  
  resetUploadingFlag : function()
  {
    this.is_uploading = false;
  },

  prepareNextUploadTask : function()
  {
    // Searching for first unuploaded file.
    var store = this.grid_panel.getStore();
    var record = null;
    
    store.each(function(r) {
      if (!record && r.get('state') == Ext.ux.UploadDialog.FileRecord.STATE_QUEUE) {
        record = r;
      }
      else {
        r.get('input_element').dom.disabled = true;
      }
    });
    
    record.get('input_element').dom.disabled = false;
    record.set('state', Ext.ux.UploadDialog.FileRecord.STATE_PROCESSING);
    record.set('note', this.i18n.note_processing);
    record.commit();
    
    this.fsa.postEvent('file-upload-start', record);
  },
   
  fireUploadStartEvent : function()
  {
    this.fireEvent('uploadstart', this);
  },
  
  removeFiles : function(file_records)
  {
    var store = this.grid_panel.getStore();
    for (var i = 0, len = file_records.length; i < len; i++) {
      var r = file_records[i];
      r.get('input_element').remove();
      store.remove(r);
    }
  },
  
  fireFileRemoveEvent : function(file_records)
  {
    for (var i = 0, len = file_records.length; i < len; i++) {
      this.fireEvent('fileremove', this, file_records[i].get('filename'));
    }
  },
  
  resetQueue : function()
  {
    var store = this.grid_panel.getStore();
    store.each(
      function(r) {
        r.get('input_element').remove();
      }
    );
    store.removeAll();
  },
  
  fireResetQueueEvent : function()
  {
    this.fireEvent('resetqueue', this);
  },
  
  uploadFile : function(record)
  {
    Ext.Ajax.request({
      url : this.url,
      params : this.base_params || this.baseParams || this.params,
      method : 'POST',
      form : this.form,
      isUpload : true,
      success : this.onAjaxSuccess,
      failure : this.onAjaxFailure,
      scope : this,
      record: record
    });
  },
   
  fireFileUploadStartEvent : function(record)
  {
    this.fireEvent('fileuploadstart', this, record.get('filename'));
  },
  
  updateRecordState : function(data)
  {
    if ('success' in data.response && data.response.success) {
      data.record.set('state', Ext.ux.UploadDialog.FileRecord.STATE_FINISHED);
      data.record.set(
        'note', data.response.message || data.response.error || this.i18n.note_upload_success
      );
    }
    else {
      data.record.set('state', Ext.ux.UploadDialog.FileRecord.STATE_FAILED);
      data.record.set(
        'note', data.response.message || data.response.error || this.i18n.note_upload_error
      );
    }
    
    data.record.commit();
  },
  
  fireUploadSuccessEvent : function(data)
  {
    this.fireEvent('uploadsuccess', this, data.record.get('filename'), data.response);
  },
  
  fireUploadErrorEvent : function(data)
  {
    this.fireEvent('uploaderror', this, data.record.get('filename'), data.response);
  },
  
  fireUploadFailedEvent : function(data)
  {
    this.fireEvent('uploadfailed', this, data.record.get('filename'));
  },
  
  fireUploadCompleteEvent : function()
  {
    this.fireEvent('uploadcomplete', this);
  },
  
  findUploadFrame : function() 
  {
    this.upload_frame = Ext.getBody().child('iframe.x-hidden:last');
  },
  
  resetUploadFrame : function()
  {
    this.upload_frame = null;
  },
  
  removeUploadFrame : function()
  {
    if (this.upload_frame) {
      this.upload_frame.removeAllListeners();
      this.upload_frame.dom.src = 'about:blank';
      this.upload_frame.remove();
    }
    this.upload_frame = null;
  },
  
  abortUpload : function()
  {
    this.removeUploadFrame();
    
    var store = this.grid_panel.getStore();
    var record = null;
    store.each(function(r) {
      if (r.get('state') == Ext.ux.UploadDialog.FileRecord.STATE_PROCESSING) {
        record = r;
        return false;
      }
    });
    
    record.set('state', Ext.ux.UploadDialog.FileRecord.STATE_FAILED);
    record.set('note', this.i18n.note_aborted);
    record.commit();
  },
  
  fireUploadStopEvent : function()
  {
    this.fireEvent('uploadstop', this);
  },
  
  repostHide : function()
  {
    this.fsa.postEvent('hide');
  },
  
  flushEventQueue : function()
  {
    this.fsa.flushEventQueue();
  },
  
  /**
   * @access private
   */
  // -------------------------------------------------------------------------------------------- //
  onWindowRender : function()
  {
    this.fsa.postEvent('window-render');
  },
  
  onWindowBeforeHide : function()
  {
    return this.isUploading() ? this.getAllowCloseOnUpload() : true;
  },
  
  onWindowHide : function()
  {
    this.fsa.postEvent('hide');
  },
  
  onWindowDestroy : function()
  {
    this.fsa.postEvent('destroy');
  },
  
  onGridRender : function()
  {
    this.fsa.postEvent('grid-render');
  },
  
  onGridSelectionChange : function()
  {
    this.fsa.postEvent('grid-selection-change');
  },
  
  onAddButtonFileSelected : function(btn)
  {
    this.fsa.postEvent('file-selected', btn);
  },
  
  onUploadButtonClick : function()
  {
    if (this.is_uploading) {
      this.fsa.postEvent('stop-upload');
    }
    else {
      this.fsa.postEvent('start-upload');
    }
  },
  
  onRemoveButtonClick : function()
  {
    var selections = this.grid_panel.getSelectionModel().getSelections();
    this.fsa.postEvent('remove-files', selections);
  },
  
  onResetButtonClick : function()
  {
    this.fsa.postEvent('reset-queue');
  },
  
  onCloseButtonClick : function()
  {
    this[this.closeAction].call(this);
  },
  
  onAjaxSuccess : function(response, options)
  {
    var json_response = {
      'success' : false,
      'error' : this.i18n.note_upload_error
    }
    try { var json_response = Ext.util.JSON.decode(response.responseText); } catch (e) {}
    
    var data = {
      record: options.record,
      response: json_response
    }
    
    if ('success' in json_response && json_response.success) {
      this.fsa.postEvent('file-upload-success', data);
    }
    else {
      this.fsa.postEvent('file-upload-error', data);
    }
  },
  
  onAjaxFailure : function(response, options)
  {
    var data = {
      record : options.record,
      response : {
        'success' : false,
        'error' : this.i18n.note_upload_failed
      }
    }

    this.fsa.postEvent('file-upload-failed', data);
  },
  
  /**
   * @access public
   */
  // -------------------------------------------------------------------------------------------- //
  startUpload : function()
  {
    this.fsa.postEvent('start-upload');
  },
  
  stopUpload : function()
  {
    this.fsa.postEvent('stop-upload');
  },
  
  getUrl : function()
  {
    return this.url;
  },
  
  setUrl : function(url)
  {
    this.url = url;
  },
  
  getBaseParams : function()
  {
    return this.base_params;
  },
  
  setBaseParams : function(params)
  {
    this.base_params = params;
  },
  
  getUploadAutostart : function()
  {
    return this.upload_autostart;
  },
  
  setUploadAutostart : function(value)
  {
    this.upload_autostart = value;
  },
  
  getAllowCloseOnUpload : function()
  {
    return this.allow_close_on_upload;
  },
  
  setAllowCloseOnUpload : function(value)
  {
    this.allow_close_on_upload;
  },
  
  getResetOnHide : function()
  {
    return this.reset_on_hide;
  },
  
  setResetOnHide : function(value)
  {
    this.reset_on_hide = value;
  },
  
  getPermittedExtensions : function()
  {
    return this.permitted_extensions;
  },
  
  setPermittedExtensions : function(value)
  {
    this.permitted_extensions = value;
  },
  
  isUploading : function()
  {
    return this.is_uploading;
  },
  
  isNotEmptyQueue : function()
  {
    return this.grid_panel.getStore().getCount() > 0;
  },
  
  getQueuedCount : function(count_processing)
  {
    var count = 0;
    var store = this.grid_panel.getStore();
    store.each(function(r) {
      if (r.get('state') == Ext.ux.UploadDialog.FileRecord.STATE_QUEUE) {
        count++;
      }
      if (count_processing && r.get('state') == Ext.ux.UploadDialog.FileRecord.STATE_PROCESSING) {
        count++;
      }
    });
    return count;
  },
  
  hasUnuploadedFiles : function()
  {
    return this.getQueuedCount() > 0;
  }
});

// ---------------------------------------------------------------------------------------------- //

var p = Ext.ux.UploadDialog.Dialog.prototype;
p.i18n = {
  title: 'Uploads',
  state_col_title: 'Status',
  state_col_width: 70,
  filename_col_title: 'Nombre del Archivo',
  filename_col_width: 230,  
  note_col_title: 'Nota',
  note_col_width: 150,
  add_btn_text: 'Agregar',
  add_btn_tip: 'Agregar archivo a la fila de uploads.',
  remove_btn_text: 'Quitar',
  remove_btn_tip: 'Quitar archivo de la fila de uploads.',
  reset_btn_text: 'Eliminar Cola',
  reset_btn_tip: 'Eliminar archivos en la cola.',
  upload_btn_start_text: 'Subir Archivo',
  upload_btn_stop_text: 'Abortar',
  upload_btn_start_tip: 'Subir Archivos en cola al servidor.',
  upload_btn_stop_tip: 'Detener Transferencia de Archivos.',
  close_btn_text: 'Cerrar',
  close_btn_tip: 'Cerrar la Ventana.',
  progress_waiting_text: 'Esperando...',
  progress_uploading_text: 'Subiendo: {0} de {1} Archivos Completos.',
  error_msgbox_title: 'Error',
  permitted_extensions_join_str: ',',
  err_file_type_not_permitted: 'El archivo con esta Extension no esta permitido.<br/>Seleccione archivos de este tipo: {1}',
  note_queued_to_upload: 'Formado para Subida.',
  note_processing: 'Subiendo...',
  note_upload_failed: 'Destino inalcanzable o Error Interno del Servidor.',
  note_upload_success: 'OK.',
  note_upload_error: 'Error de Subida.',
  note_aborted: 'Abortado por el usuario.'
}

///////////////////// Image Editor Librerias ///////////////////
Ext.namespace('Ext.ux');

Ext.ux.ImageEditor = Ext.extend(Ext.Window, {
	title: 'Editar Imagen',
	width: 500,
	height: 400,
	modal: true,
	closable: true,
	resizable: true,
	maximizable: true,
	image: '',
	imageWidth: '',
	imageHeight: '',
	imageProportions: '',
	
	initComponent: function() {
		// Send a request to create a temp image so we can edit it
		var connection = new Ext.data.Connection().request({
			url: 'kynneBackEnd/scripts_php/actions.php',
			method: 'POST',
			params: {'action': 'create_temp_image', 'image': this.image},
			scope: this,
			success: function(o) {
				var response = Ext.util.JSON.decode(o.responseText);
				
				// If a temporary image could not be created, spit an error
				if (response.success == true) {
					this.imageWidth = response.width;
					this.imageHeight = response.height;
					this.imageProportions = response.width / response.height;
					
					Ext.getCmp('resize_width').setValue(this.imageWidth);
					Ext.getCmp('resize_height').setValue(this.imageHeight);
				} else {
					// Set a status bar message
					Ext.getCmp('status_bar').setStatus({
						text: response.message,
						iconCls: 'save_warning_icon',
						clear: true
					});
					
					this.hide();
				}
			}
		});
		
		var resize_form = new Ext.form.FormPanel({
			url: 'kynneBackEnd/scripts_php/actions.php',
			method: 'POST',
			layout: 'column',
			bodyStyle: 'background-color: #E4E4E4; padding: 5px;',
			border: false,
			hidden: true,
			items: [{
				width: 90,
				layout: 'form',
				bodyStyle: 'background-color: #E4E4E4;',
				border: false,
				labelWidth: 40,
				defaults: {
					width: 40
				},
				items: [{
					xtype: 'numberfield',
					id: 'resize_width',
					name: 'resize_width',
					fieldLabel: 'Width',
					allowBlank: false,
					value: this.imageWidth,
					listeners: {
						scope: this,
						'change': function() {
							if (Ext.getCmp('lock_proportions').pressed == true) {
								Ext.getCmp('resize_height').setValue(Math.round(Ext.getCmp('resize_width').getValue() / this.imageProportions));
							}
						}
					}
				},{
					xtype: 'numberfield',
					id: 'resize_height',
					name: 'resize_height',
					fieldLabel: 'Height',
					allowBlank: false,
					value: this.imageHeight,
					listeners: {
						scope: this,
						'change': function() {
							if (Ext.getCmp('lock_proportions').pressed == true) {
								Ext.getCmp('resize_width').setValue(Math.round(Ext.getCmp('resize_height').getValue() * this.imageProportions));
							}
						}
					}
				}]
			},{
				width: 25,
				bodyStyle: 'background-color: #E4E4E4; padding-top: 13px;',
				border: false,
				items: [{
					xtype: 'button',
					id: 'lock_proportions',
					tooltip: 'Lock Proportions',
					iconCls: 'unlock_button',
					fieldLabel: 'Lock Proportions',
					enableToggle: true,
					handler: function() {
						if (this.pressed == true) {
							this.setIconClass('lock_button');
							Ext.QuickTips.register({
								target: Ext.getCmp('lock_proportions').getEl().child(Ext.getCmp('lock_proportions').buttonSelector),
								text: 'Unlock Proportions'
							});
						} else {
							this.setIconClass('unlock_button');
							Ext.QuickTips.register({
								target: Ext.getCmp('lock_proportions').getEl().child(Ext.getCmp('lock_proportions').buttonSelector),
								text: 'Lock Proportions'
							});
						}
					}
				}]
			},{
				xtype: 'button',
				text: 'Aplicar Cambios',
				scope: this,
				handler: function() {
					this.imageWidth = Ext.getCmp('resize_width').getValue();
					this.imageHeight = Ext.getCmp('resize_height').getValue();
						
					var connection = new Ext.data.Connection().request({
						url: 'kynneBackEnd/scripts_php/actions.php',
						method: 'POST',
						params: {'action': 'resize_image', 'image': this.image, 'resize_width': Ext.getCmp('resize_width').getValue(), 'resize_height': Ext.getCmp('resize_height').getValue()},
						success: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							
							if (response.success === true) {
								Ext.getDom('image_iframe').contentWindow.location.reload();
							} else {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: response.message,
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						}
					});
				}
			}]
		});
		
		var rotate_form = new Ext.form.FormPanel({
			url: 'kynneBackEnd/scripts_php/actions.php',
			method: 'POST',
			bodyStyle: 'background-color: #E4E4E4; padding: 5px',
			border: false,
			labelWidth: 50,
			hideLabels: true,
			hidden: true,
			items: [{
				xtype: 'radio',
				id: 'rotate_degrees',
				name: 'rotate_degrees',
				boxLabel: '90 Degrees',
				inputValue: '90'
			},{
				xtype: 'radio',
				name: 'rotate_degrees',
				boxLabel: '180 Degrees',
				inputValue: '180'
			},{
				xtype: 'radio',
				name: 'rotate_degrees',
				boxLabel: '270 Degrees',
				inputValue: '270'
			},{
				xtype: 'button',
				text: 'Aplicar Cambios',
				scope: this,
				handler: function() {
					// First swap the proportions on the resize form
					if (Ext.getCmp('rotate_degrees').getGroupValue() == 90 || Ext.getCmp('rotate_degrees').getGroupValue() == 270) {
						var tempWidth = this.imageHeight;
						var tempHeight = this.imageWidth;
						
						this.imageWidth = tempWidth;
						this.imageHeight = tempHeight;
						this.imageProportions = this.imageWidth / this.imageHeight;
						
						Ext.getCmp('resize_width').setValue(this.imageWidth);
						Ext.getCmp('resize_height').setValue(this.imageHeight);
					}
					
					// Now send the ajax request
					var connection = new Ext.data.Connection().request({
						url: 'kynneBackEnd/scripts_php/actions.php',
						method: 'POST',
						params: {'action': 'rotate_image', 'image': this.image, 'rotate_degrees': Ext.getCmp('rotate_degrees').getGroupValue()},
						success: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							
							if (response.success === true) {
								Ext.getDom('image_iframe').contentWindow.location.reload();
							} else {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: response.message,
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						}
					});
				}
			}]
		});
		
		var crop_form = new Ext.form.FormPanel({
			url: 'kynneBackEnd/scripts_php/actions.php',
			method: 'POST',
			bodyStyle: 'background-color: #E4E4E4; padding: 5px',
			border: false,
			labelWidth: 40,
			hidden: true,
			items: [{
				xtype: 'button',
				text: 'Aplicar Cambios',
				scope: this,
				handler: function() {
				//Aqui la funcion de crop
				}
			}]
		});

		Ext.apply(this, {
			layout: 'border',
			tbar: [{
				text: 'Guardar',
				tooltip: 'Guardar Cambios',
				iconCls: 'save_button',
				scope: this,
				handler: function() {
					var connection = new Ext.data.Connection().request({
						url: 'kynneBackEnd/scripts_php/actions.php',
						method: 'POST',
						params: {'action': 'save_image', 'image': this.image},
						scope: this,
						success: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							
							if (response.success === true) {
								this.hide();
							} else {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: response.message,
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						}
					});
				}
			},{
				text: 'Tama&ntilde;o',
				tooltip: 'Cambiar Tama&ntilde;o de la Imagen',
				iconCls: 'resize_button',
				handler: function() {
					resize_form.show();
					rotate_form.hide();
					crop_form.hide();
				}
			},{
				text: 'Rotar',
				tooltip: 'Rotar Imagen',
				iconCls: 'rotate_button',
				handler: function() {
					resize_form.hide();
					crop_form.hide();
					rotate_form.show();
				}
			},{
				text: 'Cortar',
				tooltip: 'Cortar Imagen',
				iconCls: 'crop_button',
				handler: function() {
					resize_form.hide();
					rotate_form.hide();
					crop_form.show();
				}
			}],
			items: [{
				region: 'center',
				layout: 'anchor',
				border: false,
				items: [{
					anchor: '100% 100%',
					border: false,
					html: '<iframe id="image_iframe" name="image_iframe" style="height: 100%; width: 100%;" frameborder="0" allowtransparency="true" src="kynneBackEnd/scripts_php/image.php?image=' + this.image + '"></iframe>'
				}]
			},{
				id: 'east-region',
				region: 'east',
				width: 125,
				bodyStyle: 'background-color: #E4E4E4;',
				border: false,
				items: [
					resize_form,
					rotate_form
				]
			}]
		});
		
		Ext.ux.ImageEditor.superclass.initComponent.call(this);
	},
	
	afterHide: function() {
		// Send a request to delete the temp image
		var connection = new Ext.data.Connection().request({
			url: 'kynneBackEnd/scripts_php/actions.php',
			method: 'POST',
			params: {'action': 'delete_temp_image', 'image': this.image},
			success: function(o) {
				var response = Ext.util.JSON.decode(o.responseText);
				
				// If a temporary image could not be created, spit an error
				if (response.success == true) {
				} else {
					// Set a status bar message
					Ext.getCmp('status_bar').setStatus({
						text: response.message,
						iconCls: 'save_warning_icon',
						clear: true
					});
				}
			}
		});
		
		Ext.ux.ImageEditor.superclass.afterHide.call(this);
	}
});

//Ext.reg('ImageEditor', Ext.ux.ImageEditor);
///////////////////// ///////////////////!!!!!!!!!!!!!!!!!!!!!!!!



///////////////////// ///////////////////// ///////////////////// ///////////////////// 


	
Ext.onReady(function(){

    Ext.QuickTips.init();

    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'under';
//var _existeBTN='SI';
//try{_existeBTN=document.getElementById('boton-medios');}catch(e){_existeBTN='NO';}

//if(_existeBTN=='SI'){
try{
	btn = new Ext.Button(
					{ text: textoBotonMedios
					, renderTo: 'boton-medios'
					, id: 'boton-mediosx'
					, handler: openUploader});
	
	}catch(e){
		document.body.innerHTML=document.body.innerHTML+'<div id="boton-medios" style="display:none"></div>';
		btn = new Ext.Button(
					{ text: textoBotonMedios
					, renderTo: 'boton-medios'
					, id: 'boton-mediosx'
					, handler: openUploader});
	}

//}

var ulDialog;
var ulForm;



function openUploader(){
	if(!ulDialog){
		    ulDialog = new Ext.Window({
				title: 'Administracion de Archivos',
		    	id: 'ventana-file-upload',
				width:900,
				heigth:330,
				modal: true,
				closeAction: 'hide',
				border: true,
				collapsible:true,
				collapsed:false,
				html:'<table><tr><td colspan="2"><div id="barraBotones"></div></td></tr><tr><td bgcolor="white" valign="top"><div id="treeX"></div></td><td><div id="gridFiles"></div></td></tr></table>'
				});
			}
			ulDialog.show();			
			barraBotones.render('barraBotones');
			gridFiles.render('gridFiles');
			tree.render('treeX');


}
});

var gridFiles;
var dsFiles;
var cmodelArch;
var tree;
var barraBotones;
	Ext.onReady(function(){
		Ext.QuickTips.init();
		Ext.form.Field.prototype.msgTarget = 'under';
		
		// Setup a variable for the current directory
		var current_directory = '';
		
		/* ---- Begin side_navbar tree --- */
		tree = new Ext.tree.TreePanel({
			autoScroll: true,
			animate: true,
			containerScroll: true,
			border: false,
			enableDD: true,
			ddGroup : 'fileMove',
			height:400,
			maxHeight:400,			
			loader: new Ext.tree.TreeLoader({
				dataUrl: 'kynneBackEnd/scripts_php/tree_data.json.php',
				baseParams:{raiz:''}
			}),
			root: new Ext.tree.AsyncTreeNode({
				text: 'Todos los Archivos',
				draggable: false,
				id: 'source',
				expanded: true
			}),
			listeners: {
				'click': function(node, e) {
					current_directory = node.attributes.url;
					dsFiles.load({
						params: {directory: node.attributes.url},
						callback: do_buttons
					});
				},
				'contextmenu': function(node, e) {
					node.select();
					context_menu.node = node;
					context_menu.show(e.getTarget());
				},
				'beforenodedrop': do_move
			}
		});
		
		// Add a tree sorter in folder mode
		new Ext.tree.TreeSorter(tree, {folderSort: true});
		/* ---- End side_navbar tree --- */
		
		/* ---- Begin side_navbar context menu --- */
		var context_menu = new Ext.menu.Menu({
			id: 'context_menu',
			items: [{
				text: 'Nuevo Directorio',
				iconCls: 'new_directory_button',
				handler: do_new_directory
			},{
				text: 'Cambiar Nombre',
				iconCls: 'rename_directory_button',
				handler: do_rename_directory
			},{
				text: 'Cambiar Permisos',
				iconCls: 'chmod_directory_button',
				handler: do_chmod_directory
			},{
				text: 'Eliminar Directorio',
				iconCls: 'delete_directory_button',
				handler: do_delete_directory
			}]
		});
		/* ---- End side_navbar context menu --- */

		/* ---- Begin grid --- */ 
		dsFiles = new Ext.data.GroupingStore({
			proxy: new Ext.data.HttpProxy({
			url: 'kynneBackEnd/scripts_php/grid_data.json.php',
            method: 'POST'
            }),   
            baseParams:{ruta: "",filtroTipo:'',imagenSelect:''},
			autoLoad: true,
			groupField:'type',
			sortInfo: {field: 'name', direction: 'ASC'},
			reader: new Ext.data.JsonReader({
				root: 'data',
				totalProperty: 'count'
			},[
				{name: 'name'},
				{name: 'size'},
				{name: 'type'},
				{name: 'permissions'},
				{name: 'ctime', type: 'date', dateFormat: 'timestamp'},
				{name: 'mtime', type: 'date', dateFormat: 'timestamp'},
//				{name: 'owner'},
//				{name: 'group'},
				{name: 'relative_path'},
//				{name: 'full_path'},
				{name: 'web_path'}
			])
			
		});
		
		cmodelArch = new Ext.grid.ColumnModel([
			{header: 'Nombre', dataIndex: 'name', sortable: true},
			{header: 'Tama&ntilde;o', dataIndex: 'size', sortable: true, renderer: Ext.util.Format.fileSize},
			{header: 'Tipo', dataIndex: 'type', sortable: true},
			{header: 'Prev.', dataIndex: 'permissions', sortable: true},
			{header: 'Creado', dataIndex: 'ctime', sortable: true, renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s')},
			{header: 'Modificado', dataIndex: 'mtime', sortable: true, renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s')},
//			{header: 'Owner', dataIndex: 'owner', sortable: true},
//			{header: 'Group', dataIndex: 'group', sortable: true},
			{header: 'Ruta Relativa', dataIndex: 'relative_path', sortable: true, hidden: true},
//			{header: 'Ruta Completa', dataIndex: 'full_path', sortable: true, hidden: true},
			{header: 'Ruta Web', dataIndex: 'web_path', sortable: true, hidden: true}
		]);
		
		gridFiles = new Ext.grid.GridPanel({
			border: false,
			height:290,
			width:700,
			enableDrag: true,
			ddGroup : 'fileMove',
			view: new Ext.grid.GroupingView({
				emptyText: 'No hay Archivos.',
				forceFit: true,
				showGroupName: false,
				enableNoGroups: true
			}),
			ds: dsFiles,
			cm: cmodelArch,
			listeners: {
				'rowClick': function () {
					do_buttons();
				}
			}
		});
		
		barraBotones = new Ext.StatusBar({
					id: 'status_bar',
					defaultText: '',
					defaultIconCls: '',
					statusAlign: 'right',
					items: [{
						id: 'upload_button',
						text: 'Subir Archivo',
						tooltip: 'Subir un Nuevo Archivo',
						iconCls: 'upload_button',
						handler: do_upload
					},{
						id: 'download_button',
						text: 'Descargar Archivo',
						tooltip: 'Descargar el Archivo Seleccionado',
						iconCls: 'download_button',
						disabled: true,
						handler: do_download
					},{
						id: 'rename_button',
						text: 'Renombrar',
						tooltip: 'Renombrar el Archivo Seleccionado',
						iconCls: 'rename_button',
						disabled: true,
						handler: do_rename
					},{
						id: 'chmod_button',
						text: 'Permisos',
						tooltip: 'Permisos del Archivo Seleccionado (Avanzado)',
						iconCls: 'chmod_button',
						disabled: true,
						handler: do_chmod
					},{
						id: 'delete_button',
						text: 'Eliminar',
						tooltip: 'Eliminar el Archivo Seleccionado',
						iconCls: 'delete_button',
						disabled: true,
						handler: do_delete
					},'-',{
						id: 'edit_image_button',
						text: 'Editar Imagen',
						tooltip: 'Editar Imagen Seleccionada',
						iconCls: 'edit_image_button',
						disabled: true,
						handler: do_edit_image
					}]
					});
		/* ---- End grid --- */
		
		/* --- Begin Main Layout --- 
		var viewport = new Ext.Viewport({
			layout: 'border',
			items: [{
				region: 'west',
				border: false,
				split: true,
				collapseMode: 'mini',
				width: 200,
				items: tree
			},{
				region: 'center',
				layout: 'anchor',
				border: false,
				tbar: new Ext.StatusBar({
					id: 'status_bar',
					defaultText: '',
					defaultIconCls: '',
					statusAlign: 'right',
					items: [{
						id: 'upload_button',
						text: 'Upload',
						tooltip: 'Upload New File',
						iconCls: 'upload_button',
						handler: do_upload
					},{
						id: 'download_button',
						text: 'Download',
						tooltip: 'Download Selected File',
						iconCls: 'download_button',
						disabled: true,
						handler: do_download
					},{
						id: 'rename_button',
						text: 'Rename',
						tooltip: 'Rename Selected File',
						iconCls: 'rename_button',
						disabled: true,
						handler: do_rename
					},{
						id: 'chmod_button',
						text: 'Chmod',
						tooltip: 'Chmod Selected File',
						iconCls: 'chmod_button',
						disabled: true,
						handler: do_chmod
					},{
						id: 'delete_button',
						text: 'Delete',
						tooltip: 'Delete Selected File',
						iconCls: 'delete_button',
						disabled: true,
						handler: do_delete
					},'-',{
						id: 'edit_image_button',
						text: 'Edit Image',
						tooltip: 'Edit Selected Image',
						iconCls: 'edit_image_button',
						disabled: true,
						handler: do_edit_image
					}]
				}),
				items: grid
			}]
		});
		/* --- End Main Layout --- */
		
		
		/* --- Begin Functions --- */
		function do_buttons() {
			var row = gridFiles.getSelectionModel().getSelected();
			
			if (row != null) {
				Ext.getCmp('download_button').enable();
				Ext.getCmp('rename_button').enable();
				Ext.getCmp('chmod_button').enable();
				Ext.getCmp('delete_button').enable();
				if (row.data.name.match(/\.(jpeg|jpg|gif|png)$/)) {
					Ext.getCmp('edit_image_button').enable();
				} else {
					Ext.getCmp('edit_image_button').disable();
				}
			} else {
				Ext.getCmp('download_button').disable();
				Ext.getCmp('rename_button').disable();
				Ext.getCmp('chmod_button').disable();
				Ext.getCmp('edit_image_button').disable();
			}
		}

		function do_upload() {
			upload_dialog = new Ext.ux.UploadDialog.Dialog({
				title: 'Subir Archivos',
				url: 'kynneBackEnd/scripts_php/actions.php',
				base_params: {action: 'upload', directory: current_directory, filtra:filtroUploads},
				minWidth: 400,
				minHeight: 200,
				width: 700,
				height: 350,
				reset_on_hide: false,
				allow_close_on_upload: false
			});
			upload_dialog.show('upload_button');
			upload_dialog.on("uploadcomplete", function() {
				dsFiles.reload();
			});
			upload_dialog.on("hide", function() {
				this.destroy(true);
			});
		}
		
		function do_download() {
			var row = gridFiles.getSelectionModel().getSelected();
			self.location = '/kynneBackEnd/_FILES/'+ row.data.name;
		}
		
		function do_rename() {
			var row = gridFiles.getSelectionModel().getSelected();
			
			var rename_form = new Ext.FormPanel({
				url: 'kynneBackEnd/scripts_php/actions.php',
				method: 'POST',
				bodyStyle: 'padding:10px',
				border: false,
				items: [
					new Ext.form.TextField({
						fieldLabel: 'Nombre',
						name: 'new_name',
						value: row.data.name,
						width: 'auto'
					})
				]
			});
			
			var rename_window = new Ext.Window({
				title: 'Renombrar Archivo',
				width: 340,
				closable: true,
				resizable: false,
				buttons: [{
					text: 'Guardar',
					handler: function() {
						rename_form.getForm().submit({
							waitMsg: 'Procesando Informacion, Espere...',
							params: {action: 'rename', directory: current_directory, file: row.data.name},
							success: function() {
								dsFiles.reload({
									callback: do_buttons
								});
								rename_window.hide();
							},
							failure: function() {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: 'Error: Could not rename file',
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						});
					}
				},{
					text: 'Cancel',
					handler: function() {
						rename_window.hide();
					}
				}],
				items: rename_form
			});
			
			rename_window.show('rename_button');
		}
		
		function do_chmod() {
			var row = gridFiles.getSelectionModel().getSelected();
			
			var chmod_form = new Ext.FormPanel({
				url: 'kynneBackEnd/scripts_php/actions.php',
				method: 'POST',
				bodyStyle: 'padding:10px',
				border: false,
				items: [{
					layout:'column',
					border: false,
					items: [{
						columnWidth:.33,
						xtype: 'fieldset',
						title: 'Due&ntilde;o',
						bodyStyle: 'padding: 5px;',
						autoHeight: true,
						items: [{
							xtype: 'checkbox',
							name: 'owner_read',
							boxLabel: 'Read',
							width: 'auto',
							checked: (row.data.permissions.substr(1, 1) != "-" ? true : false),
							hideLabel: true
						},{
							xtype: 'checkbox',
							name: 'owner_write',
							boxLabel: 'Write',
							width: 'auto',
							checked: (row.data.permissions.substr(2, 1) != "-" ? true : false),
							hideLabel: true
						},{
							xtype: 'checkbox',
							name: 'owner_execute',
							boxLabel: 'Execute',
							width: 'auto',
							checked: (row.data.permissions.substr(3, 1) != "-" ? true : false),
							hideLabel: true
						}]
					},{
						columnWidth:.33,
						xtype: 'fieldset',
						title: 'Grupo',
						bodyStyle: 'padding: 5px;',
						autoHeight: true,
						items: [{
							xtype: 'checkbox',
							name: 'group_read',
							boxLabel: 'Read',
							width: 'auto',
							checked: (row.data.permissions.substr(4, 1) != "-" ? true : false),
							hideLabel: true
						},{
							xtype: 'checkbox',
							name: 'group_write',
							boxLabel: 'Write',
							width: 'auto',
							checked: (row.data.permissions.substr(5, 1) != "-" ? true : false),
							hideLabel: true
						},{
							xtype: 'checkbox',
							name: 'group_execute',
							boxLabel: 'Execute',
							width: 'auto',
							checked: (row.data.permissions.substr(6, 1) != "-" ? true : false),
							hideLabel: true
						}]
					},{
						columnWidth:.33,
						xtype: 'fieldset',
						title: 'Todos',
						bodyStyle: 'padding: 5px;',
						autoHeight: true,
						items: [{
							xtype: 'checkbox',
							name: 'everyone_read',
							boxLabel: 'Read',
							width: 'auto',
							checked: (row.data.permissions.substr(7, 1) != "-" ? true : false),
							hideLabel: true
						},{
							xtype: 'checkbox',
							name: 'everyone_write',
							boxLabel: 'Write',
							width: 'auto',
							checked: (row.data.permissions.substr(8, 1) != "-" ? true : false),
							hideLabel: true
						},{
							xtype: 'checkbox',
							name: 'everyone_execute',
							boxLabel: 'Execute',
							width: 'auto',
							checked: (row.data.permissions.substr(9, 1) != "-" ? true : false),
							hideLabel: true
						}]
					}]
				}]
			});
			
			var chmod_window = new Ext.Window({
				title: 'Cambiar Permisos',
				width: 340,
				closable: true,
				resizable: false,
				buttons: [{
					text: 'Guardar',
					handler: function() {
						chmod_form.getForm().submit({
							waitMsg: 'Espere...',
							params: {action: "chmod", directory: current_directory, file: row.data.name},
							success: function() {
								dsFiles.reload({
									callback: do_buttons
								});
								chmod_window.hide();
							},
							failure: function() {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: 'Error: Could not chmod file',
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						});
					}
				},{
					text: 'Cancelar',
					handler: function() {
						chmod_window.hide();
					}
				}],
				items: chmod_form
			});
			
			chmod_window.show('chmod_button');
		}
		
		function do_delete() {
			Ext.MessageBox.confirm('Confirmaci&oacute;n', 'Desea eliminar el Archivo?', function(reponse) {
				if (reponse == "yes") {
					var row = gridFiles.getSelectionModel().getSelected();
					
					var connection = new Ext.data.Connection().request({
						url: "kynneBackEnd/scripts_php/actions.php",
						method: "POST",
						params: {action: "delete", directory: current_directory, file: row.data.name},
						success: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							
							if (response.success == true) {
								dsFiles.reload();
							} else {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: response.message,
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						},
						failure: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							// Set a status bar message
							Ext.getCmp('status_bar').setStatus({
								text: response.message,
								iconCls: 'save_warning_icon',
								clear: true
							});
						}
					});
				}
			});
		}
		
		function do_edit_image() {
			var row = gridFiles.getSelectionModel().getSelected();
			
			var edit_image_window = new Ext.ux.ImageEditor({
				image: row.data.relative_path
			});
			
			edit_image_window.show('edit_image_button');
		}
		
		function do_move(o) {
			var archivos=true;
			try{x = o.data.selections.length}catch(e){archivos=false;}
			if(archivos){
			for(i = 0; i < o.data.selections.length; i++){
				var row = o.data.selections[i];
				
				var connection = new Ext.data.Connection().request({
					url: "kynneBackEnd/scripts_php/actions.php",
					method: "POST",
					params: {'action': 'move', 'directory': current_directory, 'file': row.data.name, 'new_directory': (o.target.attributes.url ? o.target.attributes.url : '')},
					success: function(o) {
						var response = Ext.util.JSON.decode(o.responseText);
						
						if (response.success == true) {
							dsFiles.reload();
						} else {
							// Set a status bar message
							Ext.getCmp('status_bar').setStatus({
								text: response.message,
								iconCls: 'save_warning_icon',
								clear: true
							});
						}
					},
					failure: function(o) {
						var response = Ext.util.JSON.decode(o.responseText);
						// Set a status bar message
						Ext.getCmp('status_bar').setStatus({
							text: response.message,
							iconCls: 'save_warning_icon',
							clear: true
						});
					}
				});
			}
			}else{
			return false;	
			}
		}
		
		function do_new_directory() {
			Ext.MessageBox.prompt('Nuevo Directorio', 'Nombre del Nuevo Directorio', function(reponse, text) {
				if (reponse == "ok") {
					var connection = new Ext.data.Connection().request({
						url: "kynneBackEnd/scripts_php/actions.php",
						method: "POST",
						params: {action: "new_directory", directory: context_menu.node.attributes.url, new_directory: text},
						success: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							
							if (response.success == true) {
								tree.getRootNode().reload();
								tree.getRootNode().expand();
							} else {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: response.message,
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						},
						failure: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							// Set a status bar message
							Ext.getCmp('status_bar').setStatus({
								text: response.message,
								iconCls: 'save_warning_icon',
								clear: true
							});
						}
					});
				}
			});
		}
		
		function do_rename_directory() {
			Ext.MessageBox.prompt('Renombrar Directorio', 'Nuevo Nombre', function(reponse, text) {
				if (reponse == "ok") {
					var connection = new Ext.data.Connection().request({
						url: "kynneBackEnd/scripts_php/actions.php",
						method: "POST",
						params: {action: "rename_directory", directory: context_menu.node.attributes.url, new_name: text},
						success: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							
							if (response.success == true) {
								tree.getRootNode().reload();
								tree.getRootNode().expand();
							} else {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: response.message,
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						},
						failure: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							// Set a status bar message
							Ext.getCmp('status_bar').setStatus({
								text: response.message,
								iconCls: 'save_warning_icon',
								clear: true
							});
						}
					});
				}
			});
		}
		
		function do_chmod_directory() {
			Ext.MessageBox.prompt('Chmod Directory', 'Permissions', function(reponse, text) {
				if (reponse == "ok") {
					var connection = new Ext.data.Connection().request({
						url: "kynneBackEnd/scripts_php/actions.php",
						method: "POST",
						params: {action: "chmod_directory", directory: context_menu.node.attributes.url, permissions: text},
						success: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							
							if (response.success == false) {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: response.message,
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						},
						failure: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							// Set a status bar message
							Ext.getCmp('status_bar').setStatus({
								text: response.message,
								iconCls: 'save_warning_icon',
								clear: true
							});
						}
					});
				}
			});
		}
		
		function do_delete_directory() {
			Ext.MessageBox.confirm('Confirmaci&oacute;n', 'Desea Eliminar el Directorio?', function(reponse) {
				if (reponse == "yes") {
					var connection = new Ext.data.Connection().request({
						url: "kynneBackEnd/scripts_php/actions.php",
						method: "POST",
						params: {action: "delete_directory", directory: context_menu.node.attributes.url},
						success: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							//nnn
							dsFiles.reload();
							if (response.success == true) {
								tree.getRootNode().reload();
								tree.getRootNode().expand();
							} else {
								// Set a status bar message
								Ext.getCmp('status_bar').setStatus({
									text: response.message,
									iconCls: 'save_warning_icon',
									clear: true
								});
							}
						},
						failure: function(o) {
							var response = Ext.util.JSON.decode(o.responseText);
							// Set a status bar message
							Ext.getCmp('status_bar').setStatus({
								text: response.message,
								iconCls: 'save_warning_icon',
								clear: true
							});
						}
					});
				}
			});
		}
		/* --- End Functions --- */
	});
	
	
	var xl='';
var campoNavegadoFiles='';
var ImageChooser = function(config){
	this.config = config;
}

ImageChooser.prototype = {
    // cache data by image name for easy lookup
    lookup : {},
	show : function(el, callback){
		if(!this.win){
			this.initTemplates();
			
			this.store = new Ext.data.JsonStore({
				proxy: new Ext.data.HttpProxy({
				url: this.config.url,
				method: 'POST'
				}),   
				baseParams:{subCarpeta: ""},
			    root: 'images',
			    fields: [
			        'name', 'url','url2', 'path',
			        {name:'size', type: 'float'},
			        {name:'lastmod', type:'date', dateFormat:'timestamp'}
			    ],
			    listeners: {
			    	'load': {fn:function(){ this.view.select(0); }, scope:this, single:true}
			    }
			});
			this.store.load();
			
			var formatSize = function(data){
		        if(data.size < 1024) {
		            return data.size + " bytes";
		        } else {
		            return (Math.round(((data.size*10) / 1024))/10) + " KB";
		        }
		    };
			
			var formatData = function(data){
		    	data.shortName = data.name.ellipse(15);
		    	data.sizeString = formatSize(data);
		    	data.dateString = new Date(data.lastmod).format("m/d/Y g:i a");
		    	this.lookup[data.name] = data;
		    	return data;
		    };
			
		    this.view = new Ext.DataView({
				tpl: this.thumbTemplate,
				singleSelect: true,
				overClass:'x-view-over',
				itemSelector: 'div.thumb-wrap',
				emptyText : '<div style="padding:10px;">No hay Archivos.</div>',
				store: this.store,
				listeners: {
					'selectionchange': {fn:this.showDetails, scope:this, buffer:100},
					//'dblclick'       : {fn:this.doCallback, scope:this},
					'loadexception'  : {fn:this.onLoadException, scope:this},
					'beforeselect'   : {fn:function(view){
				        return view.store.getRange().length > 0;
				    }}
				},
				prepareData: formatData.createDelegate(this)
			});
			var urlCarga=(this.config.url).replace(/get-chooser-imgs.php/gi,'tree_data.json.php')
			var arbolFiles=new Ext.tree.TreeLoader({
							dataUrl: urlCarga,
							baseParams:{asdf : '', files : ''}
						});
			
			
			this.win=null;
			if(!this.win){
		    	this.win = new Ext.Window({
		    	title: 'Selecciona Archivo',
		    	id: 'img-chooser-dlg',
		    	layout: 'border',
				y:0,
				width:830,
				minWidth: 830,
				minHeight: 500,
				height:500,
				modal: true,
//				closeAction: 'hide',
				border: false,
				items:[{
					id: 'img-chooser-view',
					region: 'center',
					autoScroll: true,
					items: this.view,
                    tbar:[
						  {
						   text:'Administrar Archivos', 
						   xtype: 'button', 
						   listeners:{'click':{
							   fn:function(){
								   //document.getElementById('boton-medios').click();
								   window.top.alertaxx();
								   
								   }
							   }}
						   
						   },{
                    	text: 'Filtrar:'
                    },{
                    	xtype: 'textfield',
                    	id: 'filter',
                    	selectOnFocus: true,
                    	width: 100,
                    	listeners: {
                    		'render': {fn:function(){
						    	Ext.getCmp('filter').getEl().on('keyup', function(){
						    		this.filter();
						    	}, this, {buffer:500});
                    		}, scope:this}
                    	}
                    }, ' ', '-', {
                    	text: 'Ordenar Por:'
                    }, {
                    	id: 'sortSelect',
                    	xtype: 'combo',
				        typeAhead: true,
				        triggerAction: 'all',
				        width: 100,
				        editable: false,
				        mode: 'local',
				        displayField: 'desc',
				        valueField: 'name',
				        lazyInit: false,
				        value: 'name',
				        store: new Ext.data.SimpleStore({
					        fields: ['name', 'desc'],
					        data : [['name', 'Nombre'],['size', 'Tama&ntilde;o'],['lastmod', 'Modificado']]
					    }),
					    listeners: {
							'select': {fn:this.sortImages, scope:this}
					    }
				    }]
				},{
					id: 'img-detail-panel',
					region: 'east',
					split: true,
					width: 250,
					minWidth: 150,
					maxWidth: 250
				},{
					id: 'treeArea',
					region: 'west',
					split: true,
					width: 200,
					minWidth: 150,
					maxWidth: 250,					
					items: new Ext.tree.TreePanel({
						autoScroll: true,
						animate: true,
						containerScroll: true,
						border: false,
						enableDD: true,
						ddGroup : 'fileMove',
						loader: arbolFiles,
						root: new Ext.tree.AsyncTreeNode({
							text: 'Carpeta Raiz',
							draggable: false,
							id: 'source',
							expanded: true
						}),
						listeners: {
							'click': function(node, e) {
								current_directory = node.attributes.url;
								if(typeof(current_directory)=='undefined'){
									try{current_directory=raizDirectorio;}catch(e){current_directory='';}
									}
								eval(campoNavegadoFiles+'.chooser.store.baseParams.subCarpeta=current_directory;');
								eval(campoNavegadoFiles+'.chooser.store.reload();');
							}
						}
					})
				}],
				buttons: [{
					id: 'ok-btn',
					text: 'Seleccionar Archivo',
					handler: this.doCallback,
					scope: this
				},{
					text: 'Cancelar',
					handler: function(){ this.win.close(); },
					scope: this
				}],
				keys: {
					key: 27, // Esc key
					handler: function(){ this.win.close(); },
					scope: this
				}
			});
			}
		}
		this.reset();
	    this.win.show();
		this.callback = callback;
	},
	
	initTemplates : function(){
		this.thumbTemplate = new Ext.XTemplate(
			'<tpl for=".">',
				'<div class="thumb-wrap" id="{name}">',
				'<div class="thumb"><img src="{url}" title="{name}"></div>',
				'<span>{shortName}</span></div>',
			'</tpl>'
		);
		this.thumbTemplate.compile();
		
		this.detailsTemplate = new Ext.XTemplate(
			'<div class="details">',
				'<tpl for=".">',
					'<div class="details-info">',
					'<b>Nombre:</b>',
					'<span>{name}</span>',
					'<b>Tama&ntilde;o:</b>',
					'<span>{sizeString}</span>',
					'<b>Ultima Modificacion:</b>',
					'<span>{dateString}</span></div><br><img src="{url2}">',
				'</tpl>',
			'</div>'
		);
		this.detailsTemplate.compile();
	},
	
	showDetails : function(){
	    var selNode = this.view.getSelectedNodes();
		var detailEl='';
	    try{var detailEl = Ext.getCmp('img-detail-panel').body;}catch(e){return;}
		if(detailEl==''){return;}
		if(selNode && selNode.length > 0){
			try{selNode = selNode[0];}catch(e){return;}
			try{Ext.getCmp('ok-btn').enable();}catch(e){return;}
		    try{var data = this.lookup[selNode.id];}catch(e){return;}
       		try{detailEl.hide();}catch(e){return;}
			try{detailEl.slideIn('l', {stopFx:true,duration:.8});}catch(e){return;}
			try{this.detailsTemplate.overwrite(detailEl, data);}catch(e){return;}
            
		}else{
		    try{Ext.getCmp('ok-btn').disable();}catch(e){return;}
		    try{detailEl.update('');}catch(e){return;}
		}
	},
	
	filter : function(){
		var filter = Ext.getCmp('filter');
		this.view.store.filter('name', filter.getValue());
		this.view.select(0);
	},
	
	sortImages : function(){
		var v = Ext.getCmp('sortSelect').getValue();
    	this.view.store.sort(v, v == 'name' ? 'asc' : 'desc');
    	this.view.select(0);
    },
	
	reset : function(){
		if(this.win.rendered){
			Ext.getCmp('filter').reset();
			this.view.getEl().dom.scrollTop = 0;
		}
	    this.view.store.clearFilter();
		this.view.select(0);
	},
	
	doCallback : function(){
        var selNode = this.view.getSelectedNodes()[0];
		var callback = this.callback;
		var lookup = this.lookup;

			if(selNode && callback){
				var data = lookup[selNode.id];
				callback(data);
			}
			this.win.close();
			return
		
    },
	
	onLoadException : function(v,o){
	    this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>'); 
	}
};

String.prototype.ellipse = function(maxLength){
    if(this.length > maxLength){
        return this.substr(0, maxLength-3) + '...';
    }
    return this;
};

//Clase ChooserField
//AUTOR: Ext
//Modificaciones: RBL
Ext.form.ChooserField = function(config){
    Ext.form.ChooserField.superclass.constructor.call(this, config);
};

Ext.extend(Ext.form.ChooserField, Ext.form.TriggerField,  {
    triggerClass : 'x-form-browse-trigger',
    defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"},
	/*
	layout:"table",
    layoutConfig:{columns:2},
	items: [
			{tag: "input", type: "text", size: "10", autocomplete: "off"},
			{html:'HOLA'}
					],
	*/
	
    // Get the current value of our text field.
    
    getValue : function(){
        return Ext.form.ChooserField.superclass.getValue.call(this) || "";
    },

    // Set the current value of our text field.
    
    setValue : function(text){
        Ext.form.DateField.superclass.setValue.call(this, text);
    },

    // Trigger button clicked, create and show chooser dialog.
    
    onTriggerClick : function(){
      if(this.disabled){
        return;
      }
	  campoNavegadoFiles=this.id;
	  //alert(campoNavegadoFiles);
      this.chooser=null;
	  if (!this.chooser){
        this.chooser = new ImageChooser({url: this.loadUrl,
                                        params: this.urlParams,
                                        width: this.dlgWidth,
                                        height: this.dlgHeight});
      this.chooser.show(null, this.setField.createDelegate(this));
	  }
    },

    // Callback from chooser, put the selected file name in our text field.
    
    setField : function(data) {
      var pathc='kynneBackEnd/'+data.path
	  this.setValue(pathc); 	  
    },

    loadUrl : 'get-images.php',
    urlParams : '',
    dlgWidth : 600,
    dlgHeight : 400,
    chooser: null
});


//FORMAS ----------------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//Variables globales para crear la forma
var contenedor="";
var idTabla="";
var camposForma="";
var rutaKynneCatalogos="";
var kynneURL="";
var tituloForma="";
var widthForma="";
var idForma="";
var kynneTabla="";
var nombreNamespace="";
var kynneURLLectura="";
//Fin variables generales forma

//Variables globales para crea objetos de la forma
var varNombre='';
var labelBusquedaCampo='';
var permiteVacio=false;
var campoMuestraMv='nombre';
var campoIdMv='id';	
var caracteresMaximos=0;
var caracteresMinimos=0;
var campoLlaveTabla='id';
var campoDescripcionTabla='';
var comboEtiqueta='';
var comboTabla='';
var filtroTipo='';
var comboFiltro="";
var comboNameId="";
var validaDato;

//Fin Variables globales para crea objetos de la forma



var jsonReaderForma;
var lectorDeLaForma;
var	valorCampo=null;
var	escondeCampo=false;
var kynneIdxy=0;
var separadorCampos='';
var comboChangeFiltro=''; //Linea agregada 2009-01-30
var funcionOnChange=''; //Linea agregada 2009-05-27
var heightCampoPix='45';
//Multivalor
var widthCampoPix='150';
var manejaCantidades=false;
var filtroDiscrimina;
var campoFiltro;
var tablaMv;
var leyendaFiltro;
var camposForma;
var idObjeto;
var componenteAncho;
var componenteAlto;
var leyendaCampo;
var _textoGuardar_='';
var urlBackEnd;
//Multivalor
forma=idForma;
function generaForma(nn,cancelButton,textoGuardar){	    
	if(typeof(cancelButton)=='undefined'){cancelButton=true;}
	if(typeof(textoGuardar)=='undefined'){_textoGuardar_='Guardar';}else{_textoGuardar_=textoGuardar}
		if(cancelButton){
		botonesVar=
			[{
            text: _textoGuardar_,
			handler:function(){				
				if(typeof(noRepetidos)=='undefined'){noRepetidos='';}
				if (forma.getForm().isValid()) {
					try{tinyMCE.triggerSave();}catch(e){}
					forma.getForm().submit({params:{_noRepetidos_:noRepetidos,action:'submit',kynneTablax:kynneTabla,kynneIdx:kynneIdxy}, waitMsg:'Guardando Cambios...',
					   success: function(fp, o){
						      obj = Ext.util.JSON.decode(o.response.responseText); 
								if(typeof(obj.validacion)!='undefined'){
								Ext.Msg.alert('Error en el Campo: '+obj.campo,obj.validacion); 
								forma.findById(obj.campo).setValue('');
								try{}catch(e){document.getElementById(obj.campo).focus();}
								return
								}
						   arrCamposForma=camposForma.split(',');
						   for(x=0;x<arrCamposForma.length;x++){
								campoTratado=arrCamposForma[x].replace(/ /gi,'');
								try{forma.findById(campoTratado).setValue('');}catch(e){}
							}
							//Hago for de limpieza
							scroll(0,0);
							//forma.hide();							
								if(typeof(obj.eval)!='undefined'){
									if(obj.eval!=''){
											eval(obj.eval);
										}
									}
	                    }

					});	
					 
				}else{
					Ext.MessageBox.alert('Errores', 'Por Favor verifique los detalles marcados.');
					return;
				}

				return
			}
        },{
            text: 'Cancelar',
			handler:function(){
				forma.hide();
				return;
			}
        }]
		}else{
			botonesVar=[{
            text: _textoGuardar_,
			handler:function(){
				if (forma.getForm().isValid()) {					
					try{tinyMCE.triggerSave();}catch(e){}					
					forma.getForm().submit({params:{_noRepetidos_:noRepetidos,action:'submit',kynneTablax:kynneTabla,kynneIdx:kynneIdxy}, waitMsg:'Guardando Cambios...',
					   success: function(fp, o){
						      obj = Ext.util.JSON.decode(o.response.responseText); 
								if(typeof(obj.validacion)!='undefined'){
								Ext.Msg.alert('Error en el Campo: '+obj.campo,obj.validacion); 
								forma.findById(obj.campo).setValue('');
								try{}catch(e){document.getElementById(obj.campo).focus();}
								return
								}
						   arrCamposForma=camposForma.split(',');
	                       for(x=0;x<arrCamposForma.length;x++){
								campoTratado=arrCamposForma[x].replace(/ /gi,'');
								try{forma.findById(campoTratado).setValue('');}catch(e){}
							}		//Hago for de limpieza
							scroll(0,0);
							forma.hide();							
								if(typeof(obj.eval)!='undefined'){
									if(obj.eval!=''){
											eval(obj.eval);
										}
									}
	                    }

					});	
					 
				}else{
					Ext.MessageBox.alert('Errores', 'Por Favor verifique los detalles marcados.');
					return;
				}

				return
			}
        }]
		}
nombreNamespace=nn;
var nnn;
Ext.namespace(nombreNamespace); //Defino namespace
eval(nombreNamespace).myModule = function(){;	
Ext.QuickTips.init();
		Ext.form.Field.prototype.msgTarget = 'under'; //inits ext
  //forma=idForma;
  var creaForma=function(){	  
	if(forma==''){//Genera la Forma la forma y sus Variables	    
	    forma = new Ext.FormPanel({
        url:kynneURL,
        frame:true,
		id: idForma,
        title: tituloForma,
		labelWidth:200,
		method:'POST',
		enctype:'multipart/form-data',
        bodyStyle:'background-color:#FFFFFF; padding:5px 5px 0; text-align:left',
        width: widthForma,
		items: eval('['+camposForma+']'),	
        buttons: botonesVar
    });//Genero Forma		
		forma.render(contenedor);//rendereo la forma
		jsonReaderForma=new Ext.data.JsonReader({},eval('['+camposForma+']'));//Genero Reader
		if(kynneURLLectura=="") kynneURLLectura="kynneBackEnd/scripts_php/kynneLeeDatos.php";
		lectorDeLaForma = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({url: kynneURLLectura}),
			reader: jsonReaderForma,
			baseParams:{kynneId : kynneIdxy, kynneTabla : kynneTabla},
			remoteSort: false
		});//Genero DataStore
		lectorDeLaForma.on('load', function() {
					var arrCamposForma=camposForma.split(',');
					//hago for de llenado
					for(x=0;x<arrCamposForma.length;x++){

						campoTratado=arrCamposForma[x].replace(/ /gi,'');
						try{
						if(forma.findById(campoTratado).xtype=='itemselector'){
						//Si es multivalor entonces llena sus stores
						forma.findById(campoTratado).fromStore.reload();
						forma.findById(campoTratado).toStore.baseParams.filtro=eval("lectorDeLaForma.getAt(0).data."+campoTratado);
						forma.findById(campoTratado).toStore.reload();						
						
						}else{
							var info='';
							try{info=eval("lectorDeLaForma.getAt(0).data."+campoTratado);}catch(e){}
							info=info.replace(/\\/gi,'');
						try{eval("forma.findById(campoTratado).setValue(info)");}catch(e){}
						}
						}catch(e){}
					}

				});//Genero Event onload para el store	
	}else{
		var arrCamposForma=camposForma.split(',');			
		for(x=0;x<arrCamposForma.length;x++){
			campoTratado=arrCamposForma[x].replace(/ /gi,'');
			try{forma.findById(campoTratado).setValue('');}catch(e){}
		}		//Hago for de limpieza
		forma.show();	//Muestro la forma		
	}
		lectorDeLaForma.baseParams.kynneId = kynneIdxy;
		lectorDeLaForma.baseParams.kynneTabla = kynneTabla;
		if(typeof(kynneIdxy)!='undefined' && kynneIdxy!=''){lectorDeLaForma.load();}//Leo la Forma


}

	return {
		myPublicMethod : function(){
			var myOtherProperty = this.myPublicProperty ;
			return myPrivateVar; 
        },
		init : function(){
		 creaForma();
		} //Init (Metodo Publico que hace todo)
	}

}();	
}
	
function generaCombo(){
	comboNameId=varNombre;	
			eval("var "+varNombre+"_store =  new Ext.data.Store({proxy: new Ext.data.HttpProxy({url:rutaKynneCatalogos+'?kynneTabla='+comboTabla+'&kynneFiltro='+comboFiltro+'&campoOrder='+campoDescripcionTabla}),reader: new Ext.data.JsonReader({},[ campoLlaveTabla, campoDescripcionTabla]),fields:[campoLlaveTabla,campoDescripcionTabla]});"+varNombre+"_store.load();");
		var x1="var "+varNombre+"= new Ext.form.ComboBox({fieldLabel: comboEtiqueta,";
		var x2="store: "+varNombre+"_store,allowBlank:permiteVacio,name:comboNameId,hiddenName:comboNameId+'_hidden',id:comboNameId";
		var x6=",valueField:'"+campoLlaveTabla+"',";
		var x7="labelSeparator:separadorCampos,displayField:'"+campoDescripcionTabla+"',mode:'local',typeAhead:false,selectOnFocus:true,forceSelection:true});	";

		//---LINEAS AGREGADAS 2009-01-30---//
		var x8="";
		if(comboChangeFiltro!="") //Ejecutar funcion al seleccionar elemento del combo
		 var x8=varNombre+".addListener('select', comboChangeFiltro);";
		//---FIN AGREGADAS---//
		
		eval(x1+x2+x6+x7+x8);
		return eval(varNombre);		
	} //termina combo

function generaGrupoCheckbox(){		
comboNameId=varNombre;	
			eval("var "+varNombre+"_store =  new Ext.data.Store({proxy: new Ext.data.HttpProxy({url:'kynneBackEnd/scripts_php/kynneCatalogosLista.php?kynneTabla='+comboTabla+'&kynneFiltro='+comboFiltro+'&idtabla='+campoLlaveTabla+'&campotabla='+campoDescripcionTabla}),reader: new Ext.data.JsonReader({},[ campoLlaveTabla, campoDescripcionTabla]),fields:[campoLlaveTabla,campoDescripcionTabla]});");
		var x1="var "+varNombre+"= new Ext.ux.Multiselect({";
		var x2="store: "+varNombre+"_store,allowBlank:permiteVacio,name:comboNameId,id:comboNameId";
		//var x2="data:[['1', 'One'], ['2', 'Two'], ['3', 'Three'], ['4', 'Four'], ['5', 'Five']],allowBlank:permiteVacio,allowBlank:permiteVacio,name:comboNameId,id:comboNameId";
		var x6=",dataFields:['"+campoLlaveTabla+"','"+campoDescripcionTabla+"'],valueField:'"+campoLlaveTabla+"',";
		var x7="displayField:'"+campoDescripcionTabla+"',width:"+widthCampoPix+",height:200});	"
		var x8=varNombre+"_store.load();";

		
		eval(x1+x2+x6+x7+x8);
		return eval(varNombre);		

/*	var multiSelect1 = new Ext.ux.Multiselect({
            name:"multiselect",
            dataFields:["code", "desc"], 
            valueField:"code",
            displayField:"desc",
            width:250,
            height:200,
            allowBlank:false,
            data:[
				["1", "One"], ["2", "Two"], ["3", "Three"], ["4", "Four"], ["5", "Five"],
                ["6", "Six"], ["7", "Seven"], ["8", "Eight"], ["9", "Nine"]
             ],
            tbar:[{
                text:"Presiona la tecla CTRL para seleccionar varios elementos"
                }]
});	
return multiSelect1;*/
		
	} //termina checkbox
	 
	
function generaMV(){
	var fieldsEvaluados=eval("['"+camposFormaMultivalor.replace(/,/gi,"','")+"','Cant']");

	var storeDisponibles=new Ext.data.Store({proxy: new Ext.data.HttpProxy({url: urlBackEnd}),reader: new Ext.data.JsonReader({totalProperty: 'total',root: 'results'},fieldsEvaluados),fields:fieldsEvaluados,baseParams:{kynneTabla : tablaMv, filtro:'',campoDesc:campoFiltro,kynneFiltro:filtroDiscrimina},remoteSort: false});

	var storeSeleccionados=new Ext.data.Store({proxy: new Ext.data.HttpProxy({url: urlBackEnd}),reader: new Ext.data.JsonReader({totalProperty: 'total',root: 'results'},fieldsEvaluados),fields:fieldsEvaluados,baseParams:{kynneTabla : tablaMv, filtro:'',seleccionados:1,campoDesc:campoFiltro},remoteSort: false});

	storeDisponibles.load();
	storeSeleccionados.load();
	
	var fieldCreado={
			gridVisible:manejaCantidades,
            xtype:"itemselector",
            name:idObjeto,
			id:idObjeto,
            fieldLabel:leyendaCampo,
			allowDup:true,
			labelSeparator:separadorCampos,
            dataFields:fieldsEvaluados,
			toStore:storeSeleccionados,
            msWidth:componenteAncho,
            msHeight:componenteAlto,
            valueField:"id",
			allowBlank:false,
            displayField:campoMuestraMv,
            imagePath:"images/",
            toLegend:"Selecci&oacute;n",
            fromLegend:"Disponible",
			fromStore:storeDisponibles,
			fromBBar: new Ext.PagingToolbar({
                pageSize: 10,
                store: storeDisponibles,
                displayInfo: true,
                displayMsg: '',
                emptyMsg: ""
            }),
			fromTBar:[{
					  text: leyendaFiltro},
					  {
                    	xtype: 'textfield',
                    	id: '__filter_'+idObjeto,
                    	selectOnFocus: true,
                    	width: 100,
                    	listeners: {
                    		'render': {fn:function(x){
						    	Ext.getCmp('__filter_'+idObjeto).getEl().on('keyup', function(){
								var filter = Ext.getCmp('__filter_'+idObjeto).getValue();
								storeDisponibles.baseParams.filtro=filter;
								storeDisponibles.reload();
						    	}, this, {buffer:500});
                    		}, scope:this}
                    	}
                     }],
            toTBar:[{
                text:"Limpiar",
                handler:function(){
                    var i=forma.getForm().findField(idObjeto);
                    i.reset.call(i);
                }
            }]
        };
return fieldCreado;
}	
	

 
function generaPasswordField(){
			x1="var "+varNombre+" = new Ext.form.TextField({fieldLabel: labelBusquedaCampo,name: varNombre,id:varNombre,inputType:'password',labelSeparator:separadorCampos,vtype:'alphanum',allowBlank:permiteVacio,maxLength:caracteresMaximos,minLength:caracteresMinimos});";
			eval(x1);
			return eval(varNombre);
	}

function generaSeparadorForma(){
		x1='var '+varNombre+' = new Ext.Template("<div class=x-panel-header id='+varNombre+'>'+labelBusquedaCampo+'</div>").compile();';
			eval(x1);
			return eval(varNombre);		
	}

function generaDivForma(){
		x1='var '+varNombre+' = new Ext.Template("<div id='+varNombre+'>'+labelBusquedaCampo+'</div>").compile();';
			eval(x1);
			return eval(varNombre);		
	}

function generaTextField(){
		if(validaDato=='numerico'){
		x1="var "+varNombre+" = new Ext.form.NumberField({fieldLabel: labelBusquedaCampo,name: varNombre,id:varNombre,minValue:0,allowBlank:permiteVacio,labelSeparator:separadorCampos,maxLength:caracteresMaximos,minLength:caracteresMinimos,width:widthCampoPix});";
			eval(x1);
			widthCampoPix=150;
			return eval(varNombre);		
		}else{
		x1="var "+varNombre+" = new Ext.form.TextField({fieldLabel: labelBusquedaCampo,name: varNombre,id:varNombre,value:valorCampo,hidden:escondeCampo,vtype:validaDato,labelSeparator:separadorCampos,allowBlank:permiteVacio,maxLength:caracteresMaximos,minLength:caracteresMinimos,width:widthCampoPix,enableKeyEvents: true});";
		
		//---LINEAS AGREGADAS 2009-05-27---//
		var x8="";
		if(funcionOnChange!="") //Ejecutar funcion al seleccionar elemento del combo
		 var x8=varNombre+".addListener('keyup', funcionOnChange);";
		//---FIN AGREGADAS---//
			
			eval(x1+x8);
			widthCampoPix=150;			
			return eval(varNombre);
		}
	}

function generaTextArea(){
		if(validaDato=='numerico'){
		x1="var "+varNombre+" = new Ext.form.NumberField({fieldLabel: labelBusquedaCampo,name: varNombre,id:varNombre,minValue:0,allowBlank:permiteVacio,labelSeparator:separadorCampos,maxLength:caracteresMaximos,minLength:caracteresMinimos,width:widthCampoPix});";
			eval(x1);
			widthCampoPix=150;
			return eval(varNombre);		
		}else{
		x1="var "+varNombre+" = new Ext.form.TextArea({fieldLabel: labelBusquedaCampo,name: varNombre,id:varNombre,value:valorCampo,hidden:escondeCampo,vtype:validaDato,labelSeparator:separadorCampos,allowBlank:permiteVacio,maxLength:caracteresMaximos,minLength:caracteresMinimos,width:widthCampoPix,height:heightCampoPix});";
			eval(x1);
			widthCampoPix=150;			
			return eval(varNombre);
		}
	} //funcion

function generaHiddenField(){
x1="var "+varNombre+" = new Ext.form.TextField({fieldLabel:'',name:varNombre,id:varNombre,value:valorCampo,hidden:true});";
	eval(x1);	
	return eval(varNombre);
	}


function generaFileField(){
		x1="var "+varNombre+" = new Ext.form.ChooserField({fieldLabel: labelBusquedaCampo,labelSeparator:separadorCampos,name: varNombre,id:varNombre,readOnly:true,emptyText:'',loadUrl: 'kynneBackEnd/scripts_php/get-chooser-imgs.php?filtroTipo="+filtroTipo+"&seleccionImagen=&nada'});";
			eval(x1);
			return eval(varNombre);
	}
	
function generaImagenSelect(){
		x1="var "+varNombre+" = new Ext.form.ChooserField({fieldLabel: labelBusquedaCampo,labelSeparator:separadorCampos,name: varNombre,id:varNombre,readOnly:true,emptyText:'',loadUrl: '../../../../kynneBackEnd/scripts_php/get-chooser-imgs.php?filtroTipo="+filtroTipo+"&seleccionImagen=si'});";
			eval(x1);
			return eval(varNombre);
	}	

			
function generaDateField(){
	var x1="var "+varNombre+"= new Ext.form.DateField({fieldLabel:";
	var x2="leyendaCampoFecha,name:varNombre,labelSeparator:separadorCampos,id:varNombre,";
	var x3="width:90,allowBlank:permiteVacio,format:'Y-m-d',minValue:minimo,maxValue:maximo})";eval(x1+x2+x3);
		
			return eval(varNombre);
	}			

function generaHTMLField(){
	var fieldCreado={
				xtype: "tinymce",
				fieldLabel: labelBusquedaCampo,
				id: varNombre,
				name: varNombre,
				width: widthCampoPix,
				height: 500,
				tinymceSettings: {
					theme : "advanced",
					plugins: "safari,pagebreak,style,layer,table,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
					theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
					theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
					theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|",
					theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "bottom",
					theme_advanced_resizing : false,
					extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
					template_external_list_url : "example_template_list.js"
				}
			}

	return fieldCreado;
	}
	
	
function kynneAgregaRegistro(nn){
	kynneIdxy='';
	eval('Ext.onReady('+nn+'.myModule.init, '+nn+'.myModule, true);');	
	} //Forma de Agregado de Retistro
	
function kynneEditaRegistro(id,nn){
	kynneIdxy=id;
	eval('Ext.onReady('+nn+'.myModule.init, '+nn+'.myModule, true);');	
	} //Forma de Edicion de Registro
//FORMAS ----------------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>	

// AJAX CALLBACK  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
var	contadorVeces=1;
var	grabaCallback='';
var globalTimeout=10000;
var compara='';
function ajaxCallback(urlx,spanx,paramsx,evaluax,evaluaDespuesCallback,mensaje,abortaAjax){
	if(typeof(mensaje)=='undefined'){mensaje=true;}
	if(typeof(abortaAjax)=='undefined'){abortaAjax=false;}
	if(contadorVeces==1){
		globalTimeout=10000;
		grabaCallback="ajaxCallback('"+urlx+"','"+spanx+"','"+paramsx+"',"+evaluax+", '"+evaluaDespuesCallback+"');";
		var buffer='';
		var container='';
		if(mensaje){try{buffer=document.getElementById(spanx).innerHTML;}catch(e){}}
		try{container=document.getElementById(spanx);}catch(e){
				try{container=document.getElementById(globalspan)}catch(e){}
			}
		if(!evaluax){if(mensaje){document.getElementById(spanx).innerHTML="<br><br><img src='kynneBackEnd/images/loader.gif' />";}}
		else{if(mensaje){Ext.MessageBox.wait('Hablando con el Servidor','Por favor Espere...');}}
	}
Ext.onReady(function(){
if(compara){paramsx=paramsx+'&compara=1';}
	Ext.QuickTips.init();
					Ext.Ajax.request( 
					{	
						autoAbort:abortaAjax,
						timeout:globalTimeout,
						waitMsg: 'Guardando Cambios...',
						url: urlx, 
						params: paramsx,//end params
						failure:function(response,options){
							//Linea de for al timeout
							return;
							if(response.responseText==''||typeof(response.responseText)=='undefined'){
								contadorVeces++;
								if(contadorVeces==2){globalTimeout=20000;}
								if(contadorVeces==3){globalTimeout=20000;}
								if(contadorVeces==4){globalTimeout=120000;}
								if(contadorVeces==5){globalTimeout=120000;}								
								if(mensaje){Ext.MessageBox.wait('('+contadorVeces+') Hablando con el Servidor','Por favor Espere '+globalTimeout/1000+' segundos.');}
								if(contadorVeces==5){
									contadorVeces=1;
									globalTimeout=10000;
									Ext.MessageBox.alert('Tiempo de Respuesta Agotado','Intente de Nuevo');ext.MessageBox.wait().hide();
									return
									}
									setTimeout("ejecutaDeNuevo();",globalTimeout);
								return;
								}	//Fin timeouts
							try{Ext.MessageBox.wait().hide();}catch(e){}
							if(mensaje){Ext.MessageBox.alert('Tiempo de Respuesta Agotado','Fall&oacute; la conexion con el Servidor: <br>'+response.responseText);}
							try{container.innerHTML=buffer;}catch(e){}
							contadorVeces=1;
					
					},//end failure block       
						success:function(response,options){
							var responseData = response.responseText;
								if(!evaluax){
									try{document.getElementById(spanx).innerHTML=responseData;}catch(e){}
									}
								else{
									if(responseData!=''){
										try{eval(responseData)}catch(e){}
										var json_response = Ext.util.JSON.decode(response.responseText);
										try{eval(json_response.eval)}catch(e){}
										}
									}
							if(mensaje){Ext.MessageBox.wait().hide();}
							if(evaluaDespuesCallback!=''){eval(evaluaDespuesCallback);}
						}//end success block                                      
					 }//end request config
				); //end request  
	
	});
}//fin de la funcion
		
function ejecutaDeNuevo(){
	eval(grabaCallback);
	}
	
	
	
function Timer(intervalox,nombrex){
		this.intervalo=intervalox;
		this.parado=false;
		
		this.nombre=nombrex;
		this.setIntervalo=function(ms){
			this.intervalo=ms;
		}
		
		this.funcionesArr=new Array();
		this.Stop=function(){
			this.parado=true;
		}
		this.Play=function(){
			this.parado=false;
		}
		this.setEjecuta=function(index,funcion){
			this.funcionesArr[index]=funcion;
		}
		this.arrancaTimer=function(){
			this.ejecutaFunciones();
		}
		this.ejecutaFunciones=function(){
		var x=setTimeout(this.nombre+'.arrancaTimer();x=null;',this.intervalo);
		if(this.parado){return;}
			for(x=0;x<this.funcionesArr.length;x++){try{eval(this.funcionesArr[x])}catch(e){}}
		}
//		alert(this.intervalo);
	}

function validaAlfaNumerico(objeto){

var alphaCount=0
var numCount=0
var encuentranum=0
var encuentraletras=0

var num_valid="1234567890"

    for (var i=0; i<objeto.length; i++) {
        if (num_valid.indexOf(objeto.charAt(i)) >= 0 ) {
         numCount++
        }
    }

var alph_valid="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    for (var i=0; i<objeto.length; i++) {
        if (alph_valid.indexOf(objeto.charAt(i)) >= 0) {
            alphaCount++
        }
    }

	if(numCount>=1 && alphaCount>=1){
		return true;
	}
	else{ return false;}

}
	

function validaMail(objeto){
if(objeto==''){return true}	
		 if(objeto.indexOf('@', 0)==-1 || objeto.indexOf('.', 0)==-1 ) { 
		 return false;
		} 
		else{
		 return true;
		}
		
}


function isNumeric(value) {
  if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
  return true;
}

/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

/*
 * Software License Agreement (BSD License)
 * Copyright (c) 2008, Nige "Animal" White
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of the original author nor the names of its contributors
 *       may be used to endorse or promote products derived from this software
 *       without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * @class Ext.ux.DDView
 * <p>A DnD-enabled version of {@link Ext.DataView}. Drag/drop is implemented by adding
 * {@link Ext.data.Record}s to the target DDView. If copying is not being performed,
 * the original {@link Ext.data.Record} is removed from the source DDView.</p>
 * @constructor
 * Create a new DDView
 * @param {Object} config The configuration properties.
 */
Ext.ux.DDView = function(config) {
    if (!config.itemSelector) {
        var tpl = config.tpl;
        if (this.classRe.test(tpl)) {
            config.tpl = tpl.replace(this.classRe, 'class=$1x-combo-list-item $2$1');
        }
        else {
            config.tpl = tpl.replace(this.tagRe, '$1 class="x-combo-list-item" $2');
        }
        config.itemSelector = ".x-combo-list-item";
    }
    Ext.ux.DDView.superclass.constructor.call(this, Ext.apply(config, {
        border: false
    }));
};

Ext.extend(Ext.ux.DDView, Ext.DataView, {
    /**
     * @cfg {String/Array} dragGroup The ddgroup name(s) for the View's DragZone (defaults to undefined).
     */
    /**
     * @cfg {String/Array} dropGroup The ddgroup name(s) for the View's DropZone (defaults to undefined).
     */
    /**
     * @cfg {Boolean} copy Causes drag operations to copy nodes rather than move (defaults to false).
     */
    /**
     * @cfg {Boolean} allowCopy Causes ctrl/drag operations to copy nodes rather than move (defaults to false).
     */
    /**
     * @cfg {String} sortDir Sort direction for the view, 'ASC' or 'DESC' (defaults to 'ASC').
     */
    sortDir: 'ASC',

    // private
    isFormField: true,
    classRe: /class=(['"])(.*)\1/,
    tagRe: /(<\w*)(.*?>)/,
    reset: Ext.emptyFn,
    clearInvalid: Ext.form.Field.prototype.clearInvalid,

    // private
    afterRender: function() {
        Ext.ux.DDView.superclass.afterRender.call(this);
        if (this.dragGroup) {
            this.setDraggable(this.dragGroup.split(","));
        }
        if (this.dropGroup) {
            this.setDroppable(this.dropGroup.split(","));
        }
        if (this.deletable) {
            this.setDeletable();
        }
        this.isDirtyFlag = false;
        this.addEvents(
            "drop"
        );
    },

    // private
    validate: function() {
        return true;
    },

    // private
    destroy: function() {
        this.purgeListeners();
        this.getEl().removeAllListeners();
        this.getEl().remove();
        if (this.dragZone) {
            if (this.dragZone.destroy) {
                this.dragZone.destroy();
            }
        }
        if (this.dropZone) {
            if (this.dropZone.destroy) {
                this.dropZone.destroy();
            }
        }
    },

	/**
	 * Allows this class to be an Ext.form.Field so it can be found using {@link Ext.form.BasicForm#findField}.
	 */
    getName: function() {
        return this.name;
    },

	/**
	 * Loads the View from a JSON string representing the Records to put into the Store.
     * @param {String} value The JSON string
	 */
    setValue: function(v) {
        if (!this.store) {
            throw "DDView.setValue(). DDView must be constructed with a valid Store";
        }
        var data = {};
        data[this.store.reader.meta.root] = v ? [].concat(v) : [];
        this.store.proxy = new Ext.data.MemoryProxy(data);
        this.store.load();
    },

	/**
	 * Returns the view's data value as a list of ids.
     * @return {String} A parenthesised list of the ids of the Records in the View, e.g. (1,3,8).
	 */
    getValue: function() {
        var result = '(';
        this.store.each(function(rec) {
            result += rec.id + ',';
        });
        return result.substr(0, result.length - 1) + ')';
    },

    getIds: function() {
        var i = 0, result = new Array(this.store.getCount());
        this.store.each(function(rec) {
            result[i++] = rec.id;
        });
        return result;
    },

    /**
     * Returns true if the view's data has changed, else false.
     * @return {Boolean}
     */
    isDirty: function() {
        return this.isDirtyFlag;
    },

	/**
	 * Part of the Ext.dd.DropZone interface. If no target node is found, the
	 * whole Element becomes the target, and this causes the drop gesture to append.
	 */
    getTargetFromEvent : function(e) {
        var target = e.getTarget();
        while ((target !== null) && (target.parentNode != this.el.dom)) {
            target = target.parentNode;
        }
        if (!target) {
            target = this.el.dom.lastChild || this.el.dom;
        }
        return target;
    },

	/**
	 * Create the drag data which consists of an object which has the property "ddel" as
	 * the drag proxy element.
	 */
    getDragData : function(e) {
        var target = this.findItemFromChild(e.getTarget());
        if(target) {
            if (!this.isSelected(target)) {
                delete this.ignoreNextClick;
                this.onItemClick(target, this.indexOf(target), e);
                this.ignoreNextClick = true;
            }
            var dragData = {
                sourceView: this,
                viewNodes: [],
                records: [],
                copy: this.copy || (this.allowCopy && e.ctrlKey)
            };
            if (this.getSelectionCount() == 1) {
                var i = this.getSelectedIndexes()[0];
                var n = this.getNode(i);
                dragData.viewNodes.push(dragData.ddel = n);
                dragData.records.push(this.store.getAt(i));
                dragData.repairXY = Ext.fly(n).getXY();
            } else {
                dragData.ddel = document.createElement('div');
                dragData.ddel.className = 'multi-proxy';
                this.collectSelection(dragData);
            }
            return dragData;
        }
        return false;
    },

    // override the default repairXY.
    getRepairXY : function(e){
        return this.dragData.repairXY;
    },

	// private
    collectSelection: function(data) {
        data.repairXY = Ext.fly(this.getSelectedNodes()[0]).getXY();
        if (this.preserveSelectionOrder === true) {
            Ext.each(this.getSelectedIndexes(), function(i) {
                var n = this.getNode(i);
                var dragNode = n.cloneNode(true);
                dragNode.id = Ext.id();
                data.ddel.appendChild(dragNode);
                data.records.push(this.store.getAt(i));
                data.viewNodes.push(n);
            }, this);
        } else {
            var i = 0;
            this.store.each(function(rec){
                if (this.isSelected(i)) {
                    var n = this.getNode(i);
                    var dragNode = n.cloneNode(true);
                    dragNode.id = Ext.id();
                    data.ddel.appendChild(dragNode);
                    data.records.push(this.store.getAt(i));
                    data.viewNodes.push(n);
                }
                i++;
            }, this);
        }
    },

	/**
	 * Specify to which ddGroup items in this DDView may be dragged.
     * @param {String} ddGroup The DD group name to assign this view to.
	 */
    setDraggable: function(ddGroup) {
        if (ddGroup instanceof Array) {
            Ext.each(ddGroup, this.setDraggable, this);
            return;
        }
        if (this.dragZone) {
            this.dragZone.addToGroup(ddGroup);
        } else {
            this.dragZone = new Ext.dd.DragZone(this.getEl(), {
                containerScroll: true,
                ddGroup: ddGroup
            });
            // Draggability implies selection. DragZone's mousedown selects the element.
            if (!this.multiSelect) { this.singleSelect = true; }

            // Wire the DragZone's handlers up to methods in *this*
            this.dragZone.getDragData = this.getDragData.createDelegate(this);
            this.dragZone.getRepairXY = this.getRepairXY;
            this.dragZone.onEndDrag = this.onEndDrag;
        }
    },

	/**
	 * Specify from which ddGroup this DDView accepts drops.
     * @param {String} ddGroup The DD group name from which to accept drops.
	 */
    setDroppable: function(ddGroup) {
        if (ddGroup instanceof Array) {
            Ext.each(ddGroup, this.setDroppable, this);
            return;
        }
        if (this.dropZone) {
            this.dropZone.addToGroup(ddGroup);
        } else {
            this.dropZone = new Ext.dd.DropZone(this.getEl(), {
                owningView: this,
                containerScroll: true,
                ddGroup: ddGroup
            });

            // Wire the DropZone's handlers up to methods in *this*
            this.dropZone.getTargetFromEvent = this.getTargetFromEvent.createDelegate(this);
            this.dropZone.onNodeEnter = this.onNodeEnter.createDelegate(this);
            this.dropZone.onNodeOver = this.onNodeOver.createDelegate(this);
            this.dropZone.onNodeOut = this.onNodeOut.createDelegate(this);
            this.dropZone.onNodeDrop = this.onNodeDrop.createDelegate(this);
        }
    },

	// private
    getDropPoint : function(e, n, dd){
        if (n == this.el.dom) { return "above"; }
        var t = Ext.lib.Dom.getY(n), b = t + n.offsetHeight;
        var c = t + (b - t) / 2;
        var y = Ext.lib.Event.getPageY(e);
        if(y <= c) {
            return "above";
        }else{
            return "below";
        }
    },

    // private
    isValidDropPoint: function(pt, n, data) {
        if (!data.viewNodes || (data.viewNodes.length != 1)) {
            return true;
        }
        var d = data.viewNodes[0];
        if (d == n) {
            return false;
        }
        if ((pt == "below") && (n.nextSibling == d)) {
            return false;
        }
        if ((pt == "above") && (n.previousSibling == d)) {
            return false;
        }
        return true;
    },

    // private
    onNodeEnter : function(n, dd, e, data){
        if (this.highlightColor && (data.sourceView != this)) {
            this.el.highlight(this.highlightColor);
        }
        return false;
    },

    // private
    onNodeOver : function(n, dd, e, data){
        var dragElClass = this.dropNotAllowed;
        var pt = this.getDropPoint(e, n, dd);
        if (this.isValidDropPoint(pt, n, data)) {
            if (this.appendOnly || this.sortField) {
                return "x-tree-drop-ok-below";
            }

            // set the insert point style on the target node
            if (pt) {
                var targetElClass;
                if (pt == "above"){
                    dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
                    targetElClass = "x-view-drag-insert-above";
                } else {
                    dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
                    targetElClass = "x-view-drag-insert-below";
                }
                if (this.lastInsertClass != targetElClass){
                    Ext.fly(n).replaceClass(this.lastInsertClass, targetElClass);
                    this.lastInsertClass = targetElClass;
                }
            }
        }
        return dragElClass;
    },

    // private
    onNodeOut : function(n, dd, e, data){
        this.removeDropIndicators(n);
    },

    // private
    onNodeDrop : function(n, dd, e, data){
	//Cambio aqui
        if (this.fireEvent("drop", this, n, dd, e, data) === false) {
            return false;
        }
        var pt = this.getDropPoint(e, n, dd);
        var insertAt = (this.appendOnly || (n == this.el.dom)) ? this.store.getCount() : n.viewIndex;
        if (pt == "below") {
            insertAt++;
        }

        // Validate if dragging within a DDView
        if (data.sourceView == this) {
            // If the first element to be inserted below is the target node, remove it
            if (pt == "below") {
                if (data.viewNodes[0] == n) {
                    data.viewNodes.shift();
                }
            } else {  // If the last element to be inserted above is the target node, remove it
                if (data.viewNodes[data.viewNodes.length - 1] == n) {
                    data.viewNodes.pop();
                }
            }

            // Nothing to drop...
            if (!data.viewNodes.length) {
                return false;
            }

            // If we are moving DOWN, then because a store.remove() takes place first,
            // the insertAt must be decremented.
            if (insertAt > this.store.indexOf(data.records[0])) {
                insertAt--;
            }
        }

        // Dragging from a Tree. Use the Tree's recordFromNode function.
        if (data.node instanceof Ext.tree.TreeNode) {
            var r = data.node.getOwnerTree().recordFromNode(data.node);
            if (r) {
                data.records = [ r ];
            }
        }

        if (!data.records) {
            alert("Programming problem. Drag data contained no Records");
            return false;
        }

        for (var i = 0; i < data.records.length; i++) {
            var r = data.records[i];
            var dup = this.store.getById(r.id);
            if (dup && (dd != this.dragZone)) {
                if(!this.allowDup && !this.allowTrash){
                    Ext.fly(this.getNode(this.store.indexOf(dup))).frame("red", 1);
                    return true
                }
                var x=new Ext.data.Record();
                r.id=x.id;
                delete x;
            }
            if (data.copy) {
                this.store.insert(insertAt++, r.copy());
            } else {
                if (data.sourceView) {
                    data.sourceView.isDirtyFlag = true;
                    data.sourceView.store.remove(r);
                }
				if(!this.allowTrash)this.store.insert(insertAt++, r);
            }
            if(this.sortField){
                this.store.sort(this.sortField, this.sortDir);
            }
            this.isDirtyFlag = true;
        }
        this.dragZone.cachedTarget = null;
        return true;
    },

    // private
    onEndDrag: function(data, e) {
        var d = Ext.get(this.dragData.ddel);
        if (d && d.hasClass("multi-proxy")) {
            d.remove();
            //delete this.dragData.ddel;
        }
    },

    // private
    removeDropIndicators : function(n){
        if(n){
            Ext.fly(n).removeClass([
                "x-view-drag-insert-above",
                "x-view-drag-insert-left",
                "x-view-drag-insert-right",
                "x-view-drag-insert-below"]);
            this.lastInsertClass = "_noclass";
        }
    },

	/**
	 * Add a delete option to the DDView's context menu.
	 * @param {String} imageUrl The URL of the "delete" icon image.
	 */
    setDeletable: function(imageUrl) {
        if (!this.singleSelect && !this.multiSelect) {
            this.singleSelect = true;
        }
        var c = this.getContextMenu();
        this.contextMenu.on("itemclick", function(item) {
            switch (item.id) {
                case "delete":
                    this.remove(this.getSelectedIndexes());
                    break;
            }
        }, this);
        this.contextMenu.add({
            icon: imageUrl || AU.resolveUrl("/images/delete.gif"),
            id: "delete",
            text: AU.getMessage("deleteItem")
        });
    },

	/**
	 * Return the context menu for this DDView.
     * @return {Ext.menu.Menu} The context menu
	 */
    getContextMenu: function() {
        if (!this.contextMenu) {
            // Create the View's context menu
            this.contextMenu = new Ext.menu.Menu({
                id: this.id + "-contextmenu"
            });
            this.el.on("contextmenu", this.showContextMenu, this);
        }
        return this.contextMenu;
    },

    /**
     * Disables the view's context menu.
     */
    disableContextMenu: function() {
        if (this.contextMenu) {
            this.el.un("contextmenu", this.showContextMenu, this);
        }
    },

    // private
    showContextMenu: function(e, item) {
        item = this.findItemFromChild(e.getTarget());
        if (item) {
            e.stopEvent();
            this.select(this.getNode(item), this.multiSelect && e.ctrlKey, true);
            this.contextMenu.showAt(e.getXY());
        }
    },

	/**
	 * Remove {@link Ext.data.Record}s at the specified indices.
	 * @param {Array/Number} selectedIndices The index (or Array of indices) of Records to remove.
	 */
    remove: function(selectedIndices) {
        selectedIndices = [].concat(selectedIndices);
        for (var i = 0; i < selectedIndices.length; i++) {
            var rec = this.store.getAt(selectedIndices[i]);
            this.store.remove(rec);
        }
    },

	/**
	 * Double click fires the {@link #dblclick} event. Additionally, if this DDView is draggable, and there is only one other
	 * related DropZone that is in another DDView, it drops the selected node on that DDView.
	 */
    onDblClick : function(e){
        var item = this.findItemFromChild(e.getTarget());
        if(item){
            if (this.fireEvent("dblclick", this, this.indexOf(item), item, e) === false) {
                return false;
            }
            if (this.dragGroup) {
                var targets = Ext.dd.DragDropMgr.getRelated(this.dragZone, true);

                // Remove instances of this View's DropZone
                while (targets.indexOf(this.dropZone) !== -1) {
                    targets.remove(this.dropZone);
                }

                // If there's only one other DropZone, and it is owned by a DDView, then drop it in
                if ((targets.length == 1) && (targets[0].owningView)) {
                    this.dragZone.cachedTarget = null;
                    var el = Ext.get(targets[0].getEl());
                    var box = el.getBox(true);
                    targets[0].onNodeDrop(el.dom, {
                        target: el.dom,
                        xy: [box.x, box.y + box.height - 1]
                    }, null, this.getDragData(e));

                }
            }
        }
    },

    // private
    onItemClick : function(item, index, e){
        // The DragZone's mousedown->getDragData already handled selection
        if (this.ignoreNextClick) {
            delete this.ignoreNextClick;
            return;
        }

        if(this.fireEvent("beforeclick", this, index, item, e) === false){
            return false;
        }
        if(this.multiSelect || this.singleSelect){
            if(this.multiSelect && e.shiftKey && this.lastSelection){
                this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
            } else if (this.isSelected(item) && e.ctrlKey) {
                this.deselect(item);
            }else{
                this.deselect(item);
                this.select(item, this.multiSelect && e.ctrlKey);
                this.lastSelection = item;
            }
            e.preventDefault();
        }
        return true;
    }
});


/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

/*
 * Note that this control should still be treated as an example and that the API will most likely
 * change once it is ported into the Ext core as a standard form control.  This is still planned
 * for a future release, so this should not yet be treated as a final, stable API at this time.
 */
 
/** 
 * @class Ext.ux.MultiSelect
 * @extends Ext.form.Field
 * A control that allows selection and form submission of multiple list items. The MultiSelect control
 * depends on the Ext.ux.DDView class to provide drag/drop capability both within the list and also 
 * between multiple MultiSelect controls (see the Ext.ux.ItemSelector).
 * 
 *  @history
 *    2008-06-19 bpm Original code contributed by Toby Stuart
 *    2008-06-19 bpm Docs and demo code clean up
 * 
 * @constructor
 * Create a new MultiSelect
 * @param {Object} config Configuration options
 */
Ext.ux.Multiselect = Ext.extend(Ext.form.Field,  {
    /**
     * @cfg {String} legend Wraps the object with a fieldset and specified legend.
     */
    /**
     * @cfg {Store} store The {@link Ext.data.Store} used by the underlying Ext.ux.DDView.
     */
    /**
     * @cfg {Ext.ux.DDView} view The Ext.ux.DDView used to render the multiselect list.
     */
    /**
     * @cfg {String/Array} dragGroup The ddgroup name(s) for the DDView's DragZone (defaults to undefined). 
     */ 
    /**
     * @cfg {String/Array} dropGroup The ddgroup name(s) for the DDView's DropZone (defaults to undefined). 
     */ 
    /**
     * @cfg {Object/Array} tbar The top toolbar of the control. This can be a {@link Ext.Toolbar} object, a 
     * toolbar config, or an array of buttons/button configs to be added to the toolbar.
     */
    /**
     * @cfg {String} fieldName The name of the field to sort by when sorting is enabled.
     */
    /**
     * @cfg {String} appendOnly True if the list should only allow append drops when drag/drop is enabled 
     * (use for lists which are sorted, defaults to false).
     */
    appendOnly:false,
    /**
     * @cfg {Array} dataFields Inline data definition when not using a pre-initialised store. Known to cause problems 
     * in some browswers for very long lists. Use store for large datasets.
     */
    dataFields:[],
    /**
     * @cfg {Array} data Inline data when not using a pre-initialised store. Known to cause problems in some 
     * browswers for very long lists. Use store for large datasets.
     */
    data:[],
    /**
     * @cfg {Number} width Width in pixels of the control (defaults to 100).
     */
    width:100,
    /**
     * @cfg {Number} height Height in pixels of the control (defaults to 100).
     */
    height:100,
    /**
     * @cfg {String/Number} displayField Name/Index of the desired display field in the dataset (defaults to 0).
     */
    displayField:0,
    /**
     * @cfg {String/Number} valueField Name/Index of the desired value field in the dataset (defaults to 1).
     */
    valueField:1,
    cantidadField:2,	
    /**
     * @cfg {Boolean} allowBlank True to require at least one item in the list to be selected, false to allow no 
     * selection (defaults to true).
     */
    allowBlank:true,
    /**
     * @cfg {Number} minLength Minimum number of selections allowed (defaults to 0).
     */
    minLength:0,
    /**
     * @cfg {Number} maxLength Maximum number of selections allowed (defaults to Number.MAX_VALUE). 
     */
    maxLength:Number.MAX_VALUE,
    /**
     * @cfg {String} blankText Default text displayed when the control contains no items (defaults to the same value as
     * {@link Ext.form.TextField#blankText}.
     */
    blankText:Ext.form.TextField.prototype.blankText,
    /**
     * @cfg {String} minLengthText Validation message displayed when {@link #minLength} is not met (defaults to 'Minimum {0} 
     * item(s) required').  The {0} token will be replaced by the value of {@link #minLength}.
     */
    minLengthText:'Minimum {0} item(s) required',
    /**
     * @cfg {String} maxLengthText Validation message displayed when {@link #maxLength} is not met (defaults to 'Maximum {0} 
     * item(s) allowed').  The {0} token will be replaced by the value of {@link #maxLength}.
     */
    maxLengthText:'Maximum {0} item(s) allowed',
    /**
     * @cfg {String} delimiter The string used to delimit between items when set or returned as a string of values
     * (defaults to ',').
     */
    delimiter:',',
    
    // DDView settings
    copy:false,
    allowDup:false,
    allowTrash:false,
    focusClass:undefined,
    sortDir:'ASC',
    
    // private
    defaultAutoCreate : {tag: "div"},
    
    // private
    initComponent: function(){
        Ext.ux.Multiselect.superclass.initComponent.call(this);
        this.addEvents({
            'dblclick' : true,
            'click' : true,
            'change' : true,
            'drop' : true
        });     
    },
    
    // private
    onRender: function(ct, position){
        Ext.ux.Multiselect.superclass.onRender.call(this, ct, position);
        
        var cls = 'ux-mselect';
        var fs = new Ext.form.FieldSet({
            renderTo:this.el,
            title:this.legend,
            height:this.height,
            width:this.width,
            style:"padding:0;",
            tbar:this.tbar,
			bbar:this.bbar
        });
        //if(!this.legend)fs.el.down('.'+fs.headerCls).remove();
        fs.body.addClass(cls);

        var tpl = '<tpl for="."><div class="' + cls + '-item';
        if(Ext.isIE || Ext.isIE7){
            tpl+='" unselectable=on';
        }else{
            tpl+=' x-unselectable"';
        }
        tpl+='>{' + this.displayField + '}</div></tpl>';

        if(!this.store){
            this.store = new Ext.data.GroupingStore({
				fields: this.dataFields,
				groupField : this.displayField,
                data : this.data
            });
        }

        this.view = new Ext.ux.DDView({
            multiSelect: true, 
            store: this.store, 
            selectedClass: cls+"-selected", 
            tpl:tpl,
            allowDup:this.allowDup, 
            copy: this.copy, 
            allowTrash: this.allowTrash, 
            dragGroup: this.dragGroup, 
            dropGroup: this.dropGroup, 
            itemSelector:"."+cls+"-item",
            isFormField:false, 
            applyTo:fs.body,
            appendOnly:this.appendOnly,
            sortField:this.sortField, 
            sortDir:this.sortDir
        });

        fs.add(this.view);
        
        this.view.on('click', this.onViewClick, this);
        this.view.on('beforeClick', this.onViewBeforeClick, this);
        this.view.on('dblclick', this.onViewDblClick, this);
        this.view.on('drop', function(ddView, n, dd, e, data){
            return this.fireEvent("drop", ddView, n, dd, e, data);
        }, this);
        
        this.hiddenName = this.name;
        var hiddenTag={tag: "input", type: "hidden", value: "", name:this.name};
        if (this.isFormField) { 
            this.hiddenField = this.el.createChild(hiddenTag);
        } else {
            this.hiddenField = Ext.get(document.body).createChild(hiddenTag);
        }
        fs.doLayout();
    },
    
    // private
    initValue:Ext.emptyFn,
    
    // private
    onViewClick: function(vw, index, node, e) {
        var arrayIndex = this.preClickSelections.indexOf(index);
        if (arrayIndex  != -1)
        {
            this.preClickSelections.splice(arrayIndex, 1);
            this.view.clearSelections(true);
            this.view.select(this.preClickSelections);
        }
        this.fireEvent('change', this, this.getValue(), this.hiddenField.dom.value);
        this.hiddenField.dom.value = this.getValue();
        this.fireEvent('click', this, e);
        this.validate();        
    },

    // private
    onViewBeforeClick: function(vw, index, node, e) {
        this.preClickSelections = this.view.getSelectedIndexes();
        if (this.disabled) {return false;}
    },

    // private
    onViewDblClick : function(vw, index, node, e) {
        return this.fireEvent('dblclick', vw, index, node, e);
    },  
    
    /**
     * Returns an array of data values for the selected items in the list. The values will be separated
     * by {@link #delimiter}.
     * @return {Array} value An array of string data values
     */
    getValue: function(valueField){
        var returnArray = [];
        var selectionsArray = this.view.getSelectedIndexes();
        if (selectionsArray.length == 0) {return '';}
        for (var i=0; i<selectionsArray.length; i++) {
            returnArray.push(this.store.getAt(selectionsArray[i]).get(((valueField != null)? valueField : this.valueField)));
        }
        return returnArray.join(this.delimiter);
    },

    /**
     * Sets a delimited string (using {@link #delimiter}) or array of data values into the list.
     * @param {String/Array} values The values to set
     */
    setValue: function(values) {
        var index;
        var selections = [];
        this.view.clearSelections();
        this.hiddenField.dom.value = '';
        
        if (!values || (values == '')) { return; }
        
        if (!(values instanceof Array)) { values = values.split(this.delimiter); }
        for (var i=0; i<values.length; i++) {
            index = this.view.store.indexOf(this.view.store.query(this.valueField, 
                new RegExp('^' + values[i] + '$', "i")).itemAt(0));
            selections.push(index);
        }
        this.view.select(selections);
        this.hiddenField.dom.value = this.getValue();
        this.validate();
    },
    
    // inherit docs
    reset : function() {
        this.setValue('');
    },
    
    // inherit docs
    getRawValue: function(valueField) {
        var tmp = this.getValue(valueField);
        if (tmp.length) {
            tmp = tmp.split(this.delimiter);
        }
        else{
            tmp = [];
        }
        return tmp;
    },

    // inherit docs
    setRawValue: function(values){
        setValue(values);
    },

    // inherit docs
    validateValue : function(value){
        if (value.length < 1) { // if it has no value
             if (this.allowBlank) {
                 this.clearInvalid();
                 return true;
             } else {
                 this.markInvalid(this.blankText);
                 return false;
             }
        }
        if (value.length < this.minLength) {
            this.markInvalid(String.format(this.minLengthText, this.minLength));
            return false;
        }
        if (value.length > this.maxLength) {
            this.markInvalid(String.format(this.maxLengthText, this.maxLength));
            return false;
        }
        return true;
    }
});

Ext.reg("multiselect", Ext.ux.Multiselect);

/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

/*
 * Note that this control will most likely remain as an example, and not as a core Ext form
 * control.  However, the API will be changing in a future release and so should not yet be
 * treated as a final, stable API at this time.
 */
 
/** 
 * @class Ext.ux.ItemSelector
 * @extends Ext.form.Field
 * A control that allows selection of between two Ext.ux.MultiSelect controls.
 * 
 *  @history
 *    2008-06-19 bpm Original code contributed by Toby Stuart
 * 
 * @constructor
 * Create a new ItemSelector
 * @param {Object} config Configuration options
 */
Ext.ux.ItemSelector = Ext.extend(Ext.form.Field,  {
    msWidth:200,
    msHeight:300,
    hideNavIcons:false,
    imagePath:"",
    iconUp:"up2.gif",
    iconDown:"down2.gif",
    iconLeft:"left2.gif",
    iconRight:"right2.gif",
    iconTop:"top2.gif",
    iconBottom:"bottom2.gif",
    drawUpIcon:true,
    drawDownIcon:true,
    drawLeftIcon:true,
    drawRightIcon:true,
    drawTopIcon:true,
    drawBotIcon:true,
    fromStore:null,
    toStore:null,
    fromData:null, 
    toData:null,
    displayField:0,
    valueField:1,
	cantidadField:2,
    switchToFrom:false,
    allowDup:true,
    focusClass:undefined,
    delimiter:',',
    readOnly:false,
    toLegend:null,
    fromLegend:null,
    toSortField:null,
    fromSortField:null,
    toSortDir:'ASC',
    fromSortDir:'ASC',
    toTBar:null,
    fromTBar:null,
	fromBBar:null,
    bodyStyle:null,
    border:false,
    defaultAutoCreate:{tag: "div"},
    
    initComponent: function(){
        Ext.ux.ItemSelector.superclass.initComponent.call(this);
        this.addEvents({
            'rowdblclick' : true,
            'change' : true
        });         
    },

    onRender: function(ct, position){
        Ext.ux.ItemSelector.superclass.onRender.call(this, ct, position);

        this.fromMultiselect = new Ext.ux.Multiselect({
            legend: this.fromLegend,
            delimiter: this.delimiter,
            allowDup: this.allowDup,
            copy: this.allowDup,
            allowTrash: this.allowDup,
            dragGroup: this.readOnly ? null : "drop2-"+this.el.dom.id,
            dropGroup: this.readOnly ? null : "drop1-"+this.el.dom.id,
            width: this.msWidth,
            height: this.msHeight/2,
            dataFields: this.dataFields,
            data: this.fromData,
            displayField: this.displayField,
			cantidadField: 'Cant',
            valueField: this.valueField,
            store: this.fromStore,
            isFormField: false,
            tbar: this.fromTBar,
			bbar:this.fromBBar,
            appendOnly: true,
            sortField: this.fromSortField,
            sortDir: this.fromSortDir
        });
        this.fromMultiselect.on('dblclick', this.onRowDblClick, this);

        if (!this.toStore) {
            this.toStore = new Ext.data.SimpleStore({
                fields: this.dataFields,
                data : this.toData
            });
        }
        this.toStore.on('add', this.valueChanged, this);
        this.toStore.on('remove', this.valueChanged, this);
        this.toStore.on('load', this.valueChanged, this);
        this.toStore.on('update', this.valueChanged, this);		

        this.toMultiselect = new Ext.ux.Multiselect({
            legend: this.toLegend,
            delimiter: this.delimiter,
            allowDup: this.allowDup,
            dragGroup: this.readOnly ? null : "drop1-"+this.el.dom.id,
            //dropGroup: this.readOnly ? null : "drop2-"+this.el.dom.id+(this.toSortField ? "" : ",drop1-"+this.el.dom.id),
            dropGroup: this.readOnly ? null : "drop2-"+this.el.dom.id+",drop1-"+this.el.dom.id,
            width: this.msWidth,
            height: this.msHeight/2,
            displayField: this.displayField,
			cantidadField: 'Cant',
            valueField: this.valueField,
            store: this.toStore,
            isFormField: false,
            tbar: this.toTBar,
            sortField: this.toSortField,
            sortDir: this.toSortDir
        });
        this.toMultiselect.on('dblclick', this.onRowDblClick, this);
        
		/*      GRID CANTIDADES             */
	    var fm = Ext.form;
		//Creo cm
		var cm = new Ext.grid.ColumnModel([{
           header: this.fieldLabel,
           dataIndex: this.displayField,
           width: 130
        },{
           header: "Cantidad",
           dataIndex: 'Cant',
           width: 70,
           align: 'right',
           renderer: renderCantidad,
           editor: new fm.NumberField({
               allowBlank: false,
               allowNegative: false,
			   minValue:1,
               maxValue: 100000
           })
        }]);
		cm.defaultSortable = true;
            function renderCantidad(value){
				return value;
				if(value==0||value==''||value==null||typeof(value)=='undefined'){
				return '1'
				}else{return parseInt(value)}
            };

	//Genero Grid
	this.grid = new Ext.grid.EditorGridPanel({
        hidden:(!this.gridVisible),
		store: this.toStore,
		idPadre:this.id,
		valueField:this.valueField,
        cm: cm,
		border:0,
        width:(this.msWidth*2)+23,
        height:this.msHeight/2,
        clicksToEdit:1
    });
	this.grid.addListener('afteredit', handleEdit);
	function handleEdit(){
        var values = [];
		for (var i=0; i<this.store.getCount(); i++) {
			record = this.store.getAt(i);
			var cant=record.get('Cant');
			
			values.push(record.get(this.valueField)+'-'+cant);
        }
//		alert(values);
		this.store.commitChanges();

		}
	

		/*      GRID CANTIDADES             */
        this.icons = new Ext.Panel({header:false});		 
		this.panel = new Ext.Panel({
            border:0,
		    layout:"table",
            layoutConfig:{columns:3},
			items: [{
				html:"<div class='x-panel-header'>"+this.fieldLabel+"</div>",
				colspan: 3
			},{
				items:this.fromMultiselect
			},{
				items:this.icons
			},{
				items:this.toMultiselect
			},{
				items:this.grid,
				colspan: 3
			}]
			
        });

		/*
        p.add(grid);		
        p.add(this.switchToFrom ? this.toMultiselect : this.fromMultiselect);
        var icons = new Ext.Panel({header:false});
        p.add(icons);
        p.add(this.switchToFrom ? this.fromMultiselect : this.toMultiselect);
        */
		this.panel.render(this.el);
       // icons.el.down('.'+icons.bwrapCls).remove();
		
		
        if (this.imagePath!="" && this.imagePath.charAt(this.imagePath.length-1)!="/")
            this.imagePath+="/";
        this.iconUp = this.imagePath + (this.iconUp || 'up2.gif');
        this.iconDown = this.imagePath + (this.iconDown || 'down2.gif');
        this.iconLeft = this.imagePath + (this.iconLeft || 'left2.gif');
        this.iconRight = this.imagePath + (this.iconRight || 'right2.gif');
        this.iconTop = this.imagePath + (this.iconTop || 'top2.gif');
        this.iconBottom = this.imagePath + (this.iconBottom || 'bottom2.gif');
        var el=this.icons.getEl();
        if (!this.toSortField) {
            this.toTopIcon = el.createChild({tag:'img', src:this.iconTop, style:{cursor:'pointer', margin:'2px'}});
            el.createChild({tag: 'br'});
            this.upIcon = el.createChild({tag:'img', src:this.iconUp, style:{cursor:'pointer', margin:'2px'}});
            el.createChild({tag: 'br'});
        }
        this.addIcon = el.createChild({tag:'img', src:this.switchToFrom?this.iconLeft:this.iconRight, style:{cursor:'pointer', margin:'2px'}});
        el.createChild({tag: 'br'});
        this.removeIcon = el.createChild({tag:'img', src:this.switchToFrom?this.iconRight:this.iconLeft, style:{cursor:'pointer', margin:'2px'}});
        el.createChild({tag: 'br'});
        if (!this.toSortField) {
            this.downIcon = el.createChild({tag:'img', src:this.iconDown, style:{cursor:'pointer', margin:'2px'}});
            el.createChild({tag: 'br'});
            this.toBottomIcon = el.createChild({tag:'img', src:this.iconBottom, style:{cursor:'pointer', margin:'2px'}});
        }
        if (!this.readOnly) {
            if (!this.toSortField) {
                this.toTopIcon.on('click', this.toTop, this);
                this.upIcon.on('click', this.up, this);
                this.downIcon.on('click', this.down, this);
                this.toBottomIcon.on('click', this.toBottom, this);
            }
            this.addIcon.on('click', this.fromTo, this);
            this.removeIcon.on('click', this.toFrom, this);
        }
        if (!this.drawUpIcon || this.hideNavIcons) { this.upIcon.dom.style.display='none'; }
        if (!this.drawDownIcon || this.hideNavIcons) { this.downIcon.dom.style.display='none'; }
        if (!this.drawLeftIcon || this.hideNavIcons) { this.addIcon.dom.style.display='none'; }
        if (!this.drawRightIcon || this.hideNavIcons) { this.removeIcon.dom.style.display='none'; }
        if (!this.drawTopIcon || this.hideNavIcons) { this.toTopIcon.dom.style.display='none'; }
        if (!this.drawBotIcon || this.hideNavIcons) { this.toBottomIcon.dom.style.display='none'; }

        var tb = this.panel.body.first();
        this.el.setWidth(this.panel.body.first().getWidth());
        this.panel.body.removeClass();
        
        this.hiddenName = this.name;
        var hiddenTag={tag: "input", type: "hidden", value: "", name:this.name, id:this.id};
        this.hiddenField = this.el.createChild(hiddenTag);
        this.valueChanged(this.toStore);
    },
    
    initValue:Ext.emptyFn,
    
    toTop : function() {
        var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
        var records = [];
        if (selectionsArray.length > 0) {
            selectionsArray.sort();
            for (var i=0; i<selectionsArray.length; i++) {
                record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
                records.push(record);
            }
            selectionsArray = [];

            for (var i=records.length-1; i>-1; i--) {
                record = records[i];
                this.toMultiselect.view.store.remove(record);
                this.toMultiselect.view.store.insert(0, record);
                if(!existeValorEnSeleccion)selectionsArray.push(((records.length - 1) - i));
            }
        }
        this.toMultiselect.view.refresh();
        this.toMultiselect.view.select(selectionsArray);
    },

    toBottom : function() {
        var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
        var records = [];
        if (selectionsArray.length > 0) {
            selectionsArray.sort();
            for (var i=0; i<selectionsArray.length; i++) {
                record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
                records.push(record);
            }
            selectionsArray = [];
            for (var i=0; i<records.length; i++) {
                record = records[i];
                this.toMultiselect.view.store.remove(record);
                this.toMultiselect.view.store.add(record);
                selectionsArray.push((this.toMultiselect.view.store.getCount()) - (records.length - i));
            }
        }
        this.toMultiselect.view.refresh();
        this.toMultiselect.view.select(selectionsArray);
    },
    

    up : function() {
        var record = null;
        var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
        selectionsArray.sort();
        var newSelectionsArray = [];
        if (selectionsArray.length > 0) {
            for (var i=0; i<selectionsArray.length; i++) {
                record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
                if ((selectionsArray[i] - 1) >= 0) {
                    this.toMultiselect.view.store.remove(record);
                    this.toMultiselect.view.store.insert(selectionsArray[i] - 1, record);
                    newSelectionsArray.push(selectionsArray[i] - 1);
                }
            }
            this.toMultiselect.view.refresh();
            this.toMultiselect.view.select(newSelectionsArray);
        }
    },

    down : function() {
        var record = null;
        var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
        selectionsArray.sort();
        selectionsArray.reverse();
        var newSelectionsArray = [];
        if (selectionsArray.length > 0) {
            for (var i=0; i<selectionsArray.length; i++) {
                record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
                if ((selectionsArray[i] + 1) < this.toMultiselect.view.store.getCount()) {
                    this.toMultiselect.view.store.remove(record);
                    this.toMultiselect.view.store.insert(selectionsArray[i] + 1, record);
                    newSelectionsArray.push(selectionsArray[i] + 1);
                }
            }
            this.toMultiselect.view.refresh();
            this.toMultiselect.view.select(newSelectionsArray);
        }
    },
    
    fromTo : function() {
        var selectionsArray = this.fromMultiselect.view.getSelectedIndexes();
        var records = [];
        if (selectionsArray.length > 0) {
            for (var i=0; i<selectionsArray.length; i++) {
				record = this.fromMultiselect.view.store.getAt(selectionsArray[i]);
				records.push(record);
            }
            if(!this.allowDup)selectionsArray = [];
            for (var i=0; i<records.length; i++) {
                record = records[i];
                if(this.allowDup){
                    var x=new Ext.data.Record();
                    record.id=x.id;
                    delete x;   
                    this.toMultiselect.view.store.add(record);
                }else{
                    this.fromMultiselect.view.store.remove(record);
					this.toMultiselect.view.store.add(record);
                    selectionsArray.push((this.toMultiselect.view.store.getCount() - 1));
                }
            }
        }
        this.toMultiselect.view.refresh();
        this.fromMultiselect.view.refresh();
        if(this.toSortField)this.toMultiselect.store.sort(this.toSortField, this.toSortDir);
        if(this.allowDup)this.fromMultiselect.view.select(selectionsArray);
        else this.toMultiselect.view.select(selectionsArray);
    },
    
    toFrom : function() {
        var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
        var records = [];
        if (selectionsArray.length > 0) {
            for (var i=0; i<selectionsArray.length; i++) {
                record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
                records.push(record);
            }
            selectionsArray = [];
            for (var i=0; i<records.length; i++) {
                record = records[i];
                this.toMultiselect.view.store.remove(record);
                if(!this.allowDup){
                    this.fromMultiselect.view.store.add(record);
                    selectionsArray.push((this.fromMultiselect.view.store.getCount() - 1));
                }
            }
        }
        this.fromMultiselect.view.refresh();
        this.toMultiselect.view.refresh();
        if(this.fromSortField)this.fromMultiselect.store.sort(this.fromSortField, this.fromSortDir);
        this.fromMultiselect.view.select(selectionsArray);
    },
    
    valueChanged: function(store,x) {	
		var record = null;
        var values = [];
        for (var i=0; i<store.getCount(); i++) {
			record = store.getAt(i);
			var cant=record.get('Cant');
			values.push(record.get(this.valueField)+'-'+cant);
        }
		aaa=values;
        this.hiddenField.dom.value = values.join(this.delimiter);
        this.fireEvent('change', this, this.getValue(), this.hiddenField.dom.value);
    },
    
    getValue : function() {
        return this.hiddenField.dom.value;
    },
    
    onRowDblClick : function(vw, index, node, e) {
        return this.fireEvent('rowdblclick', vw, index, node, e);
    },
    
    reset: function(){
        range = this.toMultiselect.store.getRange();
        this.toMultiselect.store.removeAll();
        if (!this.allowDup) {
            this.fromMultiselect.store.add(range);
            this.fromMultiselect.store.sort(this.displayField,'ASC');
        }
        this.valueChanged(this.toMultiselect.store);
    }
});

Ext.reg("itemselector", Ext.ux.ItemSelector);



