/**
 * @class cgss
 * Utilidades y funciones.
 * @singleton
 */
var cgss = cgss || {
    /**
     * La versión del framework
     * @type String
     */
	version: "0.1"
};

/**
 * @class cgss.UI
 * Permite la creacioón de interfaces basadas en Extjs
 * @singleton
 */
cgss.UI = {
    /**
     * La versión de las utilidades de GUI
     * @type String
     */
	version: "0.1"
};

// cgss.UI.titulos
//
Ext.apply(cgss.UI,{
	/**
	 * @class cgss.UI.titulos
	 * Titulos comúnes para toda la aplicación.
	 * @singleton
	 */
	titulos: {
		/**
         * @type String
         */
        nuevo:"Adicionar ",
		asociar:"Asociar ",
		desasociar:"Desasociar ",
		debe_seleccionar_registro: "Debe seleccionar un registro ",
		/**
         * @type String
         */
		guardar: "Guardar",
		/**
         * @type String
         */
		editar: "Editar",
		/**
         * @type String
         */
		cancelar: "Cancelar",
		/**
         * @type String
         */
		guardando_registro: "Guardando",
		/**
         * @type String
         */
		resultado_exitoso: "Resultado exitoso",
		/**
         * @type String
         */
		guardado_exitoso: "Registro guardado con éxito",
		/**
         * @type String
         */
        operacion_exitosa: "Operación realizada con éxito",
		/**
         * @type String
         */
		borrado_exitoso: "Registro eliminado con éxito",
		/**
         * @type String
         */
		eliminar: "Eliminar ",
		/**
         * @type String
         */
        adicionar: "Adicionar ",
        /**
         * @type String
         */
		espere: "Por favor espere ",
		/**
         * @type String
         */
		error: "Error",
		/**
         * @type String
         */
		error_registros_invalido: "Verifique la información de los campos del registro",
		/**
         * @type String
         */
		error_comunicacion_servidor: "Hay un error de conexión/comunicación con el servidor",
		/**
         * @type String
         */
		error_validacion_formulario: "Hay errores en algunos valores para este formulario",
		/**
         * @type String
         */
		confirmacion: "Confirmación",
		/**
         * @type String
         */
		confirmar_eliminacion: " ¿Está seguro de eliminar este registro?",
		/**
         * @type String
         */
		cargando: "Cargando ",
		/**
		* string
		*/
		consultar:"Consultar ",
		/**
		* string
		*/
		refrescar: "Refrescar ",

		detalles: "Detalle ",

		sobrepasado: "Ha sobrepasado el máximo de caracteres",

		vacio: "Este Campo es Obligatorio",

		filtrar:"Filtrar",

		validacion_titulo_ventana: "Campos Inválidos",

		validacion_contenido: "Verifique que todos los campos obligatorios tengan datos y que estén correctamente digitados",

		detallado_por_tabla: "Detallado por tabla",

		error_login: 'Verifique su usuario y/o contraseña',

		campos_vacios_login: "",

		subir:"Cargar",

		subir_plano: "Subir ",

		reporte:"Ver reporte ",

		asignar: "Asignar ",
		//Jobs
		remover:"Remover",
		activar:"Activar",
		desactivar:"Desactivar",
		actualizar:"Actualizar",
		historia:"Historia",
		ejecutar:"Ejecutar",
		programacion:"Programación"
	}
	
   ,mensajes: {
   		/**
		* string 
		*/
		error: "Se ha producido un error en el sistema <br> Intente nuevamente."
   }
	
});

Ext.apply(cgss.UI,{
	format: {
 		"int": "0,000",
//		"float": "0,000.0000",
 		"true": "SI",
 		"false": "NO"//,
//		"floatvolumen": "0,000.00"
	}
});

Ext.apply(cgss.UI, {
    /**
    * Muestra un mensaje describiendo un error.
    * @param {String} title
    * @param {string} msg
    * @method mostrar_error
    */
    mostrar_error: function(title, msg) {
        Ext.Msg.alert(title, msg);
        /*Ext.Msg.show({
            title: title,
            msg: msg,
            buttons: Ext.Msg.OK,
            //icon: Ext.Msg.ERROR,
            minWidth: 600
            //maxHeight: 400
        });*/
    }
});


Ext.apply(cgss.UI, {
	/**
	 * Se utiliza para capturar un error en la carga de los datos del
	 * formulario.
	 * @param {String} form
	 * @param {Object} acion
	 * @method cgss.UI.formulario_error
	 */
 	formulario_error: function(form, action){
		switch(action.failureType){
			case Ext.form.Action.CLIENT_IVALID:
				cgss.UI.mostrar_error(
					cgss.UI.titulos.error,
					cgss.UI.titulos.error_registros_invalido);
				break;
			case Ext.form.Action.CONNECT_FAILURE:
				cgss.UI.mostrar_error(
					cgss.UI.titulos.error,
					"<b>Status</b><br/>" +
					cgss.UI.titulos.error_comunicacion_servidor + "<br/><br/>" +
					"<b>Detalle:</b>" + action.response.responseText);
				break;
			case Ext.form.Action.SERVER_INVALID:
				cgss.UI.mostrar_error(
					cgss.UI.titulos.error,
					action.result.message
				);
				break;}
		if (typeof action.result !== "undefined"){
			if (action.result.success == false){
				cgss.UI.mostrar_error(
					cgss.UI.titulos.error,
					action.result.message
				);
				return true;
			}
		}
	}
});


Ext.apply(cgss.UI,{
	/**
	 * Se utiliza para mostrar un mensaje de error en la carga
	 * de los datos de un store.
	 * @param {Object} proxy
	 * @param {String} type
	 * @param {Object} action
	 * @param {Object} options
	 * @param {Object} response
	 * @param {Object} arg
	 * @method cgss.UI.store_load_error
	 */
	store_load_error: function(proxy, type, action, options, response, arg){
		var error = "Error";
		if (Ext.isObject(response) && Ext.isDefined(response.Message))
		{
			error = response.Message;
		}
		else
		{
			if (type == "response"){
				try{
					error = Ext.decode(response.responseText).message;
				}catch(err){
					error = response.responseText;
				}
			}else{
				error = response.responseText;
			}
		}
		cgss.UI.mostrar_error(
			cgss.UI.titulos.error,
			error
		);
	}
});

/**
 * @class cgss.UI.iconos
 * Ruta de iconos comunes para utilizar en la aplicacion
 * @singleton
 */
Ext.apply(cgss.UI,{
	iconos: {
	    asociar              : "images/cog_go.png",
		adicionar            : "images/application_form_add.png",
		guardar              : "images/disk.png",
		editar               : "images/application_form_edit.png",
		cancelar             : "images/cancel.png" ,
		desasociar           : "images/table_link.png",
		eliminar             : "images/application_form_delete.png",
		importar             : "images/application_put.png"	,
		consultar            : "images/find.png",
		refrescar            : "images/arrow_refresh.png",
		reporte              : "images/report.png",
		menu_filtrar         : "images/magnifier.png",
		detallado_por_tabla  : "images/table_link.png",
		ayuda                : "images/help.png",
		consultar_grafico    : "images/chart_line_add.png",
		ver_detalle          : "images/table_link.png",
		nuevo                : "images/tag_blue_add.png",
		subir                : "images/world_go.png",
		cargar               : "images/world_add.png",
		printer              : "images/printer.png",
		manual               : "images/add.png",
		contadores           : "images/application_add.png",
		activar              : "images/connect.png",
		desactivar           : "images/disconnect.png",
		programacion         : "images/wrench_orange.png",
		ejecutar             : "images/exclamation.png",
		historia             : "images/script.png",
		actualizar           : "images/transmit.png",
		detalles             : "images/page.png",
		flecha_abajo		 : "images/arrow_down.png" ,
		resultado_anterior   : "images/resultset_previous.png",
		resultado_siguiente  : "images/resultset_next.png" ,
		flecha_arriba		: "images/arrow_up.png",
		flecha_abajo_top	   : "images/arrow_down_top.png",
		flecha_arriba_top	   : "images/arrow_up_top.png",
		add					      : "images/add.png",
		_delete			            : "images/delete.png",
		aplicacion           : "images/application.png",
		scada                : "images/application_view_tile.png",
		bitacora             : "images/script.png",
		datos_calculados     : "images/cog_go.png",
		cerrar_sesion		: "images/door_out.png",
        error               : "images/error.png"
	}}
);


Ext.apply(cgss.UI,{
	/**
	 * @type Array
	 * Un arreglo de objetos para definir meses
	 * @static
	 */
	meses:[
		{ id: 1, mes: "[01] Enero" },
		{ id: 2, mes: "[02] Febrero" },
		{ id: 3, mes: "[03] Marzo" },
		{ id: 4, mes: "[04] Abril" },
		{ id: 5, mes: "[05] Mayo" },
		{ id: 6, mes: "[06] Junio" },
		{ id: 7, mes: "[07] Julio" },
		{ id: 8, mes: "[08] Agosto" },
		{ id: 9, mes: "[09] Septiembre" },
		{ id: 10, mes: "[10] Octubre" },
		{ id: 11, mes: "[11] Noviembre" },
		{ id: 12, mes: "[12] Diciembre" }
	]}
);

Ext.apply(cgss.UI,{
	/**
	 * Se utiliza para ejecutar llamados post
	 * de los datos de un store.
	 * @param {conf} proxy
	 * @method cgss.UI.eliminar
	 */
	 enviar_post: function(conf){


	 	Ext.Ajax.request({
			url: conf.url,
			timeout: 120000,
			method: "POST",
			headers: {"Content-Type":"application/json"},
			params: Ext.encode(conf.params),
			success: conf.success || function(response){
				var r = Ext.decode(response.responseText);

				if (!r.success){
					cgss.UI.mostrar_error(
						cgss.UI.titulos.error,
						r.message
					);
					if (conf.after_all) conf.after_all();
					return false;
	            }


				Ext.Msg.alert(
					conf.msg_titulo || cgss.UI.titulos.resultado_exitoso,
					conf.msg_success || r.message ///cgss.UI.titulos.operacion_exitosa
				);
				if (conf.on_success){
					conf.on_success(r);
				}
				if (conf.after_all) conf.after_all();
			},
			failure: conf.failure || function(response){
				cgss.UI.mostrar_error(
					cgss.UI.titulos.error,
					response.responseText
				);
				if (conf.on_failure) conf.on_failure();
				if (conf.after_all) conf.after_all();
			}
		});
	 }
});

Ext.apply(cgss.UI,{
	/**
	 * Se utiliza eliminar registros en base a una URL
	 * de los datos de un store.
	 * @param {conf} proxy
	 * @method cgss.UI.eliminar
	 */
	eliminar: function(conf){

		Ext.Ajax.request({
			url: conf.url,
			method: "POST",
			headers: {"Content-Type":"application/json"},
			params: Ext.encode(conf.params),
			success: conf.success || function(){
				Ext.Msg.alert(
					cgss.UI.titulos.resultadoExitoso,
					cgss.UI.titulos.borrado_exitoso
				);
				if (conf.on_delete){
					conf.on_delete
				}
			},
			failure: conf.failure || function(response){
				cgss.UI.mostrar_error(
					cgss.UI.titulos.error,
					response.responseText
				);
			}
		});
	}
});


cgss.UI.include = function(url) {
  $.ajax({
    url: url,
    async: false,
    dataType: "script"
  });
}


//traduccion

/*
cgss.UI.show_error = cgss.UI.mostrar_error;
cgss.UI.form_error = cgss.UI.formulario_error;
cgss.UI.icons = cgss.UI.iconos;
*/


Date.parseFunctions["date_wcf"] = function(input){
  input = input.replace(
        new RegExp('/Date\\((-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)/', 'g'),
            '(new Date($1))');
    return eval(input);
};

cgss.UI.return_wcf_date = function(input){
	var f = input.replace(
        new RegExp('/Date\\((-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)/', 'g'),
            '(new Date($1))');

        /*new RegExp('/Date\\((-?\\d+)\\)/', 'g'),
            '(new Date($1 + (1*24*60*60*1000) ))');   */
    return eval(f);
}

cgss.UI.date_value_to_wcf = function(date_value){
	return "\/Date(" + date_value.getTime() + ")\/";
}

cgss.UI.date_wcf_to_format = function( value, format ) {
	var nfecha = cgss.UI.return_wcf_date( value );
	return nfecha.format( format );
}

cgss.UI.dateToUTC = function (date) {
    return String.leftPad(date.getUTCDate(), 2, "0") + "/" + 
        String.leftPad(date.getUTCMonth() + 1, 2, "0") + "/" + 
        date.getUTCFullYear();    
};

cgss.UI.arrayIndexOf = function(array, value){
   var i=0;
   while(i<array.length && array[i]!=value){
       i++;
   }
   if (i==array.length) return -1;
   else return i;
}

cgss.UI.arrayContains = function(array, value){
    return cgss.UI.arrayIndexOf(array, value) >= 0;
}

cgss.UI.removeFromArray = function(array, value){
	if (!cgss.UI.arrayContains(array, value)){
		return array;
	}
	var arr = [];
	for (var i=0; i<array.length; i++){
		if (array[i] != value){
			arr.push[arr];
		}
	}
	return arr;
}

cgss.UI.isUndefined = function(obj){
	return (typeof obj === "undefined");
}

cgss.UI.isNull = function(obj){
	return obj == null;
}

cgss.UI.find = function(arr, key, value){
	var tmp = [];
	for (var i=0; i<arr.length; i++){
		if (arr[i][key] == value){
			tmp.push(arr[i]);
		}
	}
	return tmp;
}

cgss.UI.arrayIndexObject = function(arr, key, value){
	var tmp = [];
	for (var i=0; i<arr.length; i++){
		if (arr[i][key] == value){
			return i;
		}
	}
	return -1;
}

cgss.UI.addProperty = function(obj, key, value){
	obj[key] = value;
}

cgss.UI.removeProperty = function(obj, key){
	var tmp = {};
	for(a in obj){
		if (a != key){
			tmp[a] = obj[a];
		}
	}
	return tmp;
}


// esta funcion evalua una entidad (como si fuera una expresion)
// y trae el resultado
cgss.UI.get_expresion = function ( config ) {
	Ext.Ajax.request({
		url: "expresion.svc/expresion/evaluar"
		, method: "GET"
		, params: {
			expresion: config.expresion
			, variables: config.variables || "[]"
		}
		, success: function (res) {
			var res_decoded = Ext.decode( res.responseText );
			try{
				res_decoded = Ext.decode ( res_decoded );
			}catch(e){}
			config.success( res_decoded );
		}
		, failure: function (res) {
			if ( config.failure )
				config.failure( res );
            Ext.Msg.alert( "Error", res.statusText );
            return false;
      }
		
	});
};

cgss.UI.get_raw_expresion = function ( config ) {
	Ext.Ajax.request({
		url: "expresion.svc/expresion/evaluar"
		, method: "GET"
		, params: {
			expresion: config.expresion
			, variables: config.variables || "[]"
		}
		, success: function (res) {
			config.success( res );
		}
		, failure: function (res) {
			if ( config.failure )
				config.failure( res );
		}
	});
};


cgss.UI.insertar_entidad = function ( config ) {
		Ext.Ajax.request ( {
			url: "expresion.svc/entidad/insertar"
			, method: "POST"
			, headers: {"Content-Type":"application/json"}
			, params: Ext.encode ({
				nombre_entidad: config.nombre
				, valores: config.valores
			})
			, success: function( res ){
				config.success ( res );
				/*
				var obj = Ext.decode(res.responseText);
				if ( !obj.success ) {
					cgss.UI.mostrar_error("Error en la inserción", obj.message);
				} else {
					Ext.Msg.alert("Perfil Operación", "Registro Insertado con Exito!");
				}
				*/
			}
			, failure: config.faiulre || function ( res ){
				cgss.UI.mostrar_error("Error", "Error al insertar la entidad: " + res.responseText)
			}
		} );
	}

cgss.UI.eliminar_entidad = function ( config ) {
		// alert (id);
		cgss.UI.enviar_post( {
			url: "expresion.svc/entidad/eliminar"
			, params: {
				nombre_entidad: config.nombre
				, id: config.id
			}
			, success: function( res ) {
				if (config.success)
					config.success( res );
				else {
					Ext.Msg.alert("Resultado", "Registro Eliminado con Éxito!");
					// cargar_datos();
				}
			}
		} );
	};

cgss.UI.editar_entidad = function ( config ) {
	Ext.Ajax.request ( {
		url: "expresion.svc/entidad/editar"
		, method: "POST"
		, headers: {"Content-Type":"application/json"}
		, params: Ext.encode ({
			nombre_entidad: config.nombre
			, id: config.id
			, valores: config.valores
		})
		, success: function( res ){
				config.success ( res );
			}
			, failure: config.faiulre || function ( res ){
				cgss.UI.mostrar_error("Error", "Error al insertar la entidad: " + res.responseText)
			}
	} );
};

cgss.UI.evaluar_expresion_tpl = function ( config ){
  var texto = config.texto;
  var variables = config.variables;
  Ext.Ajax.request({
    url: "expresion.svc/expresion/evaluar_tpl_txt"
    , method: "GET"
    , params: {
      texto: texto.replace(/\n/g,'').replace(/\r/,'')
      , obj_valores: variables.replace(/\n/g, '')
    }
    , success: config.success
  } );
};

cgss.UI.evaluar_expresion_nombre = function ( config ){
  var nombre = config.nombre;
  var variables = config.variables;
  Ext.Ajax.request({
    url: "expresion.svc/expresion/evaluar_tpl"
    , method: "GET"
    , params: {
      nombre: config.nombre
      , obj_valores: config.variables.replace(/\n/g, '')
    }
    , success: function ( res ) {
      var res_decoded = Ext.decode( res.responseText );
      try{
        res_decoded = Ext.decode( res_decoded );
      }catch(e){}
      config.success( res_decoded );
    }
    , failure: config.faiulre || function ( res ){
        cgss.UI.mostrar_error("Error", "Error al evaluar la expresion: " + res.statusText)
      }
  });
};

cgss.UI.evaluar_expresion_nombre_simple = function ( config ) {
  var nombre = config.nombre;
  var fn_success = config.success;
  var fn_failure = config.failure;
  Ext.Ajax.request({
    url: "expresion.svc/expresion/evaluar_expresion_nombre"
    , method: "GET"
    , params: {
      nombre: nombre
    }
    , success: function ( res ) {
      var res_decoded = Ext.decode( res.responseText );
      try{
        res_decoded = Ext.decode( res_decoded );
      }catch(e){}
      fn_success( res_decoded );
    }
    , failure: fn_failure || function ( res ) {
      cgss.UI.mostrar_error("Error", "Error al evaluar la expresion: " + res.statusText)
    }
  });
};

cgss.UI.evaluar_expresion_nombre_prefix = function ( config ) {
  var nombre = config.nombre;
  var prefix = config.prefix;
  var fn_success = config.success;
  var fn_failure = config.failure;
  Ext.Ajax.request({
    url: "expresion.svc/expresion/evaluar_expresion_nombre_prefix"
    , method: "GET"
    , params: {
      nombre: nombre
      , prefix: prefix
    }
    , success: function ( res ) {
      var res_decoded = Ext.decode( res.responseText );
      try{
        res_decoded = Ext.decode( res_decoded );
      }catch(e){}
      fn_success( res_decoded );
    }
    , failure: fn_failure || function ( res ) {
      cgss.UI.mostrar_error("Error", "Error al evaluar la expresion: " + res.statusText)
    }
  });
};

cgss.UI.decode = function ( text ) {
	var res_decoded = Ext.decode( res.responseText );
  try{
    res_decoded = Ext.decode( res_decoded );
  }catch(e){}
  return res_decoded;
};

cgss.UI.evaluar_select = function ( config ) {
	var query = config.query;
	var success = config.success;
	var failure = config.failure;
	Ext.Ajax.request({
		url: "expresion.svc/expresion/evaluar_select"
		, params: {
			query: query
		}
		, method: "GET"
		, success: function ( res ){
			success( cgss.UI.decode(res) );
		}
		, failure: failure || function ( res ) {
      cgss.UI.mostrar_error("Error", "Error al evaluar la expresion: " + res.statusText)
		}	
	});			
};

// Recoge las expresiones de las funciones de validacion 
// y devluelve el boooleano correspondiente a su validación
// en conjunto
cgss.UI.evaluarExpresiones = function (listaExpresiones) {
    var tempBool = true;
    _.each(listaExpresiones, function (expresion) {
        // console.log(expresion.data,eval("(" + expresion.data + ")"));
        tempBool = (eval("(" + expresion.data + ")") && tempBool);                
    });
    return tempBool;
}

// SOBRE ESCRIBIR ALGUNA FUNCIONALIDAD DE EXTJS

// Sobre escribe la lectura para las teclas especiales "convirtiendo"
// el enter en un tab
//*
/*
Ext.override(Ext.form.Field, {
	fireKey: function(e){
		if(e.isSpecialKey()){
			if (e.getKey() == e.ENTER){
			}
		}
	}
});
*/

Ext.override(Ext.grid.CellSelectionModel, {
    onEditorKey: function(field, e){
        // if (e.getKey() == e.ENTER) e.stopEvent();        
        if(e.getKey() == e.TAB || e.getKey() == e.ENTER){
            this.handleKeyDown(e);            
        }
    },

    handleKeyDown : function(e){
        if(!e.isNavKeyPress()){
            return;
        }
        var k = e.getKey(),
            g = this.grid,
            s = this.selection,
            sm = this,
            ed = g.activeEditor || g.lastEdit,
            walk = function(row, col, step){
                return g.walkCells(
                    row,
                    col,
                    step,
                    // g.isEditor && g.editing ? sm.acceptsNav : sm.isSelectable, // *** handle tabbing while editorgrid is in edit mode
                    sm.acceptsNav,
                    sm
                );
            },
            cell, newCell, r, c, ae;

        switch(k){
            case e.ESC:
            case e.PAGE_UP:
            case e.PAGE_DOWN:
                // do nothing
                break;
            default:
                // *** call e.stopEvent() only for non ESC, PAGE UP/DOWN KEYS
                e.stopEvent();
                break;
        }
        /*
        if(!s){
            cell = walk(0, 0, 1); // *** use private walk() function defined above
            if(cell){
                this.select(cell[0], cell[1]);
            }
            return;
        }
        */
        
        // cell = s.cell;  // currently selected cell
        // r = cell[0];    // current row
        // c = cell[1];    // current column
        
        r = ed.row;
        c = ed.col;

        switch(k){
            case e.TAB:
                if(e.shiftKey){
                    newCell = walk(r, c - 1, -1);
                }else{
                    newCell = walk(r, c + 1, 1);
                }
                break;
            case e.DOWN:
                newCell = walk(r + 1, c, 1);
                break;
            case e.UP:
                newCell = walk(r - 1, c, -1);
                break;
            case e.RIGHT:
                newCell = walk(r, c + 1, 1);
                break;
            case e.LEFT:
                newCell = walk(r, c - 1, -1);
                break;
            case e.ENTER:                
                if(this.moveEditorOnEnter !== false){
                    // e.stopEvent();
                    if(e.shiftKey){
                        newCell = walk(r, c - 1, -1);
                    }else{
                        newCell = walk(r, c + 1, 1);
                    }
                    
                    if (g.isEditor && !g.editing) {
                        g.startEditing(r, c);
                        // return;
                    }    
                } /* else {
                    if (g.isEditor && !g.editing) {
                        g.startEditing(r, c);
                        return;
                    }                    
                }*/
                break;
        }

        if(newCell){
            // *** reassign r & c variables to newly-selected cell's row and column
            r = newCell[0];
            c = newCell[1];

            this.select(r, c); // *** highlight newly-selected cell and update selection

            if(g.isEditor && g.editing){ // *** handle tabbing while editorgrid is in edit mode
                // ae = g.activeEditor;
                ae = g.activeEditor || g.lastEdit;
                if(ae && ae.field.triggerBlur){
                    // *** if activeEditor is a TriggerField, explicitly call its triggerBlur() method
                    ae.field.triggerBlur();
                }
                g.startEditing(r, c);
            }
        }
    }
});

//*
Ext.override(Ext.form.Field, {
    fireKey: function(e) {
        if (e.isSpecialKey()) {
            this.fireEvent('specialkey', this, e);
            if (e.getKey() == e.ENTER) {
                if (!this.inEditor) {
                    // console.log("enter field fireKey", this);
                    var els = Ext.query("input[readonly!=''][type!=hidden]");
                    var index = els.indexOf(Ext.getDom(this.id));
                    if (index < els.length - 1) {
                        var id2 = els[index + 1].id;
                        var cmp2 = Ext.getCmp(id2);
                        if (typeof cmp2 != undefined) {
                            cmp2.focus();
                        }
                        //cmp2.focus();
                    }
                }
                // e.stopEvent();
            }
        }
    }
});
//*/
/*
Ext.override(Ext.grid.RowSelectionModel,{
    onEditorKey : function(field, e) {   
        if (e.getKey() == e.ENTER) {
            var k = e.getKey(), newCell, g = this.grid,ed = g.activeEditor || g.lastActiveEditor; 
            e.stopEvent();
            if(e.shiftKey){
                newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
            }else{
                newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
            }
            if(newCell){
                g.startEditing(newCell[0], newCell[1]);
            } 
        }
    }    
});
//*/




Ext.override(Ext.grid.RowSelectionModel, {
    onEditorKey: function(field, e) {
        var k = e.getKey(), 
            newCell, 
            g = this.grid, 
            last = g.lastEdit,
            ed = g.activeEditor || g.lastEdit,
            shift = e.shiftKey,
            ae, r, c;
            
        if(k == e.TAB){
            e.stopEvent();
            // ed.completeEdit();
            if(shift){
                newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
            }else{
                newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
            }
        }else if(k == e.ENTER){
            if(this.moveEditorOnEnter !== false){
                if(shift){
                    newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
                }else{
                    newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
                }
            }
        }
        if(newCell){
            r = newCell[0];
            c = newCell[1];

            // this.onEditorSelect(r, last.row);

            if(g.isEditor && g.editing){ // *** handle tabbing while editorgrid is in edit mode
                ae = g.activeEditor;
                if(ae && ae.field.triggerBlur){
                    // *** if activeEditor is a TriggerField, explicitly call its triggerBlur() method
                    ae.field.triggerBlur();
                }
            }
            g.startEditing(r, c);
        }
    }
});


// Cuando un campo de texto tiene el foco, va a seleccionar todo el texto
// contenido en el
Ext.override(Ext.form.TextField, {
	onFocus : function(){
        this.preFocus();
        if(this.focusClass){
            this.el.addClass(this.focusClass);
        }
        if(!this.hasFocus){
            this.hasFocus = true;
            this.startValue = this.getValue();

            // selecciono el texto en el campo
            this.selectText();

            this.fireEvent('focus', this);
        }
    }
});

Ext.override(Ext.data.Store,{
    addField: function(field){
        field = new Ext.data.Field(field);
        this.recordType.prototype.fields.replace(field);
        if(typeof field.defaultValue != 'undefined'){
            this.each(function(r){
                if(typeof r.data[field.name] == 'undefined'){
                    r.data[field.name] = field.defaultValue;
                }
            });
        }
    },
    removeField: function(name){
        this.recordType.prototype.fields.removeKey(name);
        this.each(function(r){
            delete r.data[name];
            if(r.modified){
                delete r.modified[name];
            }
        });
    }
});
Ext.override(Ext.grid.ColumnModel,{
    addColumn: function(column, colIndex){
        if(typeof column == 'string'){
            column = {header: column, dataIndex: column};
        }
        var config = this.config;
        this.config = [];
        if(typeof colIndex == 'number'){
            config.splice(colIndex, 0, column);
        }else{
            colIndex = config.push(column);
        }
        this.setConfig(config);
        return colIndex;
    },
    removeColumn: function(colIndex){
        var config = this.config;
        this.config = [config[colIndex]];
        config.splice(colIndex, 1);
        this.setConfig(config);
    }
});
Ext.override(Ext.grid.GridPanel,{
    addColumn: function(field, column, colIndex){
        if(!column){
            if(field.dataIndex){
                column = field;
                field = field.dataIndex;
            } else{
                column = field.name || field;
            }
        }
        this.store.addField(field);
        return this.colModel.addColumn(column, colIndex);
    },
    removeColumn: function(name, colIndex){
        this.store.removeField(name);
        if(typeof colIndex != 'number'){
            colIndex = this.colModel.findColumnIndex(name);
        }
        if(colIndex >= 0){
            this.colModel.removeColumn(colIndex);
        }
    }
});



