Ext.SSL_SECURE_URL='images/default/s.gif';
Ext.BLANK_IMAGE_URL='images/default/s.gif';

Ext.onReady(function(){
	
    Ext.QuickTips.init();
	
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
				 
	if ((!Ext.isGecko)&&(!is_chrome)){
		Ext.getDom('MsgAlertBrowser').style.display='';	
	}
	
	Ext.form.Field.prototype.msgTarget = 'side';
	Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
	
	var objReset = new Ext.Button({
		id 				: 'login-reset',
		type 			: 'reset',
		text 			: 'Limpiar'
	})
	
    function validaLogin(){
        if ((!Ext.isGecko)&&(!is_chrome)){
            Ext.Msg.alert('Advertencia', 'Utilize Mozilla FireFox, para poder acceder al modulo.');
            return ;
        }
        Ext.get('loginPassword').dom.value = hex_md5(Ext.get('loginPassword').dom.value);
        Ext.getCmp('login-form').getForm().submit({
            method      : 'GET',
            waitTitle   : 'Conectando........',
            waitMsg     : 'Enviando Datos......',
            success     : function(form, action){
                obj = Ext.util.JSON.decode(action.response.responseText);
                if (obj.resetclave=='N'){
                    location.href='framework.php';
                }else{
                    winChange.show();
                }
            },
            failure     : function(form, action){
                if (action.failureType == 'server'){
                    obj = Ext.util.JSON.decode(action.response.responseText);
                    Ext.Msg.alert('Usuario Fallido!', obj.errors.reason);
                }else{
                    if (typeof(action.response)=='undefined'){
                        Ext.Msg.alert('Atencion!', 'Debe ingresar los parametros' );
                    }else{
                        Ext.Msg.alert('Atencion!', 'Authentication server is unreachable : ' + action.response.responseText);
                    }
                }
                Ext.getCmp('login-form').getForm().reset();
            }
        }); 
    }
    
	// se crea la ventana que contenera al loginform
	// pasamos los objetos que utilizaremos en la ventana que son logopanel y login.  
    var win = new Ext.Window({
		shadowOffset	: 12,
		buttonAlign		: 'right',
		closable		: false,
		draggable		: false,
		height			: 300,
		id				: 'frmlogin-logo',
		layout			:'border',
		minHeight		: 250,
		minWidth		: 430,
		plain			: false,
		resizable		: false,
		iconCls			: 'user',
		width			: 450,
		title			: 'Inicio Sesi&oacute;n',
		listeners       : {
            'beforeshow'    : function(scope){
    			Ext.getCmp('loginUsername').focus();
            }
		},
		border			: true,
		items			: [
            {
                baseCls			: 'x-plain-body',
                id				: 'login-logo',
                region			: 'center',
                xtype           : 'panel'
            },{
                xtype           : 'form',
        		labelPad		: 25,
        		baseCls			: 'x-plain',
        		baseParams		: { module: 'login' },
        		defaultType		: 'textfield',
        		height			: 135,
        		id				: 'login-form',
                buttonAlign		: 'right',
                url				: 'xmlprocess/control_access.php',
        		buttonAlign		: 'right',
        		region			: 'south',
        		bodyStyle		: 'padding:2px 69px 0',        
        		items			: [
        			{ 
                        fieldLabel		: 'Usuario', 
                        id				: 'loginUsername',
        				name			: 'loginUsername',
        				allowBlank		: false,
        				blankText 		: 'Digite su Usuario',
                        style			: 'overflow-x:hidden;',
                        stateful 		: true,
                        enableKeyEvents : true,
        				width			: 150,
        				height 			: 20,
                        listeners       : {
                            'keypress'		: function(obj, e){
                                if (e.getKey() == e.ENTER){
                                    if (Ext.getCmp('loginPassword').getValue().length >0){
                                        validaLogin();
                                    }
                                }
                            }
                        }				
                    },{
                  		xtype			: 'panel',
        		  		width 			: 310,
        				layout			: 'column',
        				bodyBorder 		: false,
        				bodyStyle		: 'background-color: transparent;',
        				border 			: false,				
        				items 			: [
        					{
        						width 		: 125,
        						border 		: false,
        						bodyStyle	: 'background-color: transparent;',
        						items 		: [
        							{
        								xtype		: 'label', 
        								html		: '&nbsp;',
        								bodyStyle	: 'background-color: transparent;',
        								width 		: 200
        							}
        						]
        					},{
        						fieldLabel	: '',
        						id			: 'lblUserName',
        						xtype 		: 'label',
        						text 		: '(ejemplo : 0200014044)',
        						bodyStyle	: 'background-color: transparent; color: #666666',
        						height 		: 20
        					}
        				]
        			},{
        				fieldLabel		: 'Contrase&ntilde;a',
        				id				: 'loginPassword',
        				name			: 'loginPassword', 
        				inputType		: 'password',
        				allowBlank		: false,
        				blankText 		: 'Digite su Contrase&ntilde;a',
        				style			: 'overflow-x:hidden;',
                        enableKeyEvents : true,
        				width			: 150,
                        listeners       : {
                            'keypress'		: function(obj, e){
                                if (e.getKey() == e.ENTER){
                                    if (Ext.getCmp('loginPassword').getValue().length >0){
                                        validaLogin();
                                    }
                                }
                            }
                        }				
                    },{
        				id				: 'accion',
        				name			: 'accion',
        				xtype			: 'hidden',
        				value			: '1'
        			},{
        				xtype			: 'panel',
        				width 			: 310,
        				layout			: 'column',
        				bodyBorder 		: false,
        				bodyStyle		: 'background-color: transparent;',
        				border 			: false,
        				items 			: [
        					{
        						width 		: 200,
        						border 		: false,
        						bodyStyle	: 'background-color: transparent;',
        						items 		: [
        							{
        								xtype		: 'label', 
        								html		: '&nbsp;',
        								bodyStyle	: 'background-color: transparent;',
        								width 		: 200
        							}
        						]
        					},{
        						width 		: 110,
        						ctCls		: 'x-plain',
        						border 		: false,
        						items		: [
        							{
        								ctCls		: 'x-plain',
        								xtype		: 'button',
        								id			: 'login-win',
        								text		: 'Iniciar sesi&oacute;n',
        								iconCls 	: 'icon_btn_inicio',
        								formBind	: true,
        								tooltip		: 'Click Aqui',
        								handler		: function(){
        									validaLogin();
        				                } 
        							}				        	
        						]
        					}
        				]
        			}
        		],
        		bbar			: [
        			{
        				type 			: 'button',
        				id 				: 'login-reg',
        				text 			: 'Registrar',
        				iconCls 		: 'icon_btn_register',
        				tooltip 		: 'Registrar nuevo usuario',
        				handler 		: function (){
        					winRegNewUser.show();
        				}
        			},{
        				type 			: 'button',
        				id 				: 'login-forgot',
        				iconCls 		: 'icon_btn_forgot',
        				text 			: 'Olvide mi contrase&ntilde;a?',
        				tooltip 		: 'Permite recuperar su contraseņa',
        				handler 		: function (){
        					Ext.Ajax.request({
        						url			: 'xmlprocess/control_access.php',
        						method 		: 'GET',
        						success		: function(response, options){
        							obj = Ext.util.JSON.decode(response.responseText);
        							if (obj.proceso==false){
        								Ext.Msg.alert('Error',obj.errors.reason);
        							}else{
        								Ext.getCmp('winForgotPassword').show();
        							}
        						},
        						failure: function(){
        							Ext.Msg.alert("Error en la consulta al Servidor");
        						},
        						params: { 
        							accion	: '5',  
        							step 	: 0 
        						}
        					});
        						
        				}
        			}
        		] 
            }]
	});
	
	var objPwd = new Ext.ux.PasswordField({
		fieldLabel 			: 'Nueva Contrase&ntilde;a',
		id 					: 'txtPwd',
		name 				: 'txtPwd',
		minLengthText 		: 'La Contrase&ntilde;a no puede ser menor de 5 caracteres',
		minLength 			: 5,
		maxLengthText 		: 'La Contrase&ntilde;a no puede ser mayor de 20 caracteres',
		maxLength 			: 20,
		width				: 120,
		height 				: 80,
		showCapsWarning		: true,
		showStrengthMeter	: true,
		pwStrengthTest		: function(pw) {
			return (pw.length * 10);
		}		
	});
	
	var winChange = new Ext.Window({
		hadowOffset			: 12,
		buttonAlign			: 'right',
		closable			: false,
		draggable			: false,
		height				: 230,
		id					: 'NewPwd',
		name				: 'NewPwd',
		plain				: false,
		resizable			: false,
		iconCls				: 'user',
		width				: 400,
		title				: 'Cambio de Contrase&ntilde;a por Seguridad',
		focus 				: function(){
			Ext.get('txtPwdAnt').focus();	
	    },
	    modal 				: true,
	    border				: true,
	    items				: [
			{
				id				: 'frmChangeClave',
				xtype 			: "form",
				width 			: 400,
				height 			: 200,
				labelWidth 		: 140,
				bodyStyle 		: 'padding: 10px 15px 10px 10px;',
				items 			: [
					{
	  					xtype 			: 'label',
						width 			: 300,
				    	pageX 			: 20,
				    	text 			: "Por motivos de seguridad, debe cambiar su clave antes de ingresar a Intranet",
				    	style 			: 'color: darkblue; font-weight: bolder; font-size: 11px;'
					},{
						xtype 			: 'textfield',
						fieldLabel 		: 'Contrase&ntilde;a Anterior',
						id 				: 'txtPwdAnt',
						name 			: 'txtPwdAnt',
						width			: 120,
						inputType 		: 'password',
						minLength 		: 5,
						minLengthText 	: 'La Contrase&ntilde;a no puede ser menor de 5 digitos'
					},{
						xtype			: 'uxpassword',
						fieldLabel 		: 'Nueva Contrase&ntilde;a',
						id 				: 'txtPwd',
						name 			: 'txtPwd',
						minLengthText 	: 'La Contrase&ntilde;a no puede ser menor de 5 caracteres',
						minLength 		: 5,
						maxLengthText 	: 'La Contrase&ntilde;a no puede ser mayor de 20 caracteres',
						maxLength 		: 20,
						width			: 120,
						showCapsWarning	: true,
						showStrengthMeter: true,
						pwStrengthTest	: function(pw) {
							return (pw.length * 10);
						}
					},{
						xtype 			: 'textfield',
						fieldLabel 		: 'Verificar Contrase&ntilde;a',
						initialPassField : 'txtPwd',
						width			: 120,
						id 				: 'txtPwdVeri',
						name 			: 'txtPwdVeri',
						inputType 		: 'password',
						vtype			: 'password',
						initialPassField: 'txtPwd'
					}
				],
				buttons : [
					{
				  		type 			: 'button',
			  			text 			: 'Guardar',
			  			onClick 		: function () {
			  				var codpwdant=Ext.getCmp('txtPwdAnt').getValue();
						  	var codpwdnew=Ext.getCmp('txtPwd').getValue();
							var codpwdnewval=Ext.getCmp('txtPwdVeri').getValue();
							if (!Ext.getCmp('frmChangeClave').getForm().isValid()){
								Ext.Msg.alert('Error','Verifique los parametros por favor');
					  			return;
							}
							if (codpwdnew!=codpwdnewval){
					  			Ext.Msg.alert('Error','La validacion de la contrase&ntilde;a no es correcta');
					  			return;
					  		}
					  		Ext.Ajax.request({
					  			waitMsg		: 'Eliminando el registro, por favor espere...',
							  	url			: 'xmlprocess/control_access.php',
							  	params 		: "accion=2&pass="+codpwdnew+"&oldpwd="+codpwdant,
							  	method		: 'GET',
								success		: function(response, options) {
									var o = {};
									try {
										o = Ext.util.JSON.decode(response.responseText);
										if(true !== o.proceso) {
											Ext.MessageBox.alert('Error Interno', o.errors.reason);
										}else {
											Ext.Msg.alert('Informacion','Se ha actualizado su contrase&ntilde;a', 
												function(btn){
													location.href='framework.php';
												}
											);
										}
									}catch(e) {
										Ext.MessageBox.alert('Error en Decodificacion', 'El Documento no puede decodificarse : ' + response.responseText);
									}
								},
								failure: function(form, action) {
									Ext.MessageBox.alert('Fallo en operacion','Hubo un fallo al tratar de acceder al m&oacute;dulo');
								},
								timeout		: '30000'
							});
						},
						width 			: 90
					}
				]
			}
		]
	});
    
    
	Ext.getCmp('frmlogin-logo').show();  
    
});