/**
 * Login
 * 2008-08-07
 * @author Rolf Meyer
 */
rcm.Login = function(){
console.log(this);	


	// Passwort ändern Fenster
	var passwordWindow = new Ext.Window({
        layout:'fit',
        width:350,
        height:150,
		y:100,
        closable: false,
        resizable: false,
        plain: true,
        border: false,
		modal: true,
        items: new Ext.FormPanel({ 
			id:'passwordResetForm',
	        labelWidth:120,
	        frame:true, 
	        title:'Passwort ändern', 
			monitorValid:true,
			monitorResize:true,
			defaultType:'textfield',

	        items:[
				{ 
	                fieldLabel:'Neues Passwort', 
	                name:'password', 
	                allowBlank:false ,
					width:200,
					inputType:'password',
					id:'passwordFieldNS'
					
	            },
				{
					fieldLabel:'Neues Passwort wiederholen',
					name:'passwordRep',
					allowBlank:false,
					width:200,
					inputType:'password',
					validator:function(val){
						if(val != Ext.getCmp('passwordFieldNS').getRawValue()){
							return "Die Passwörter stimmen nicht überein";
						}else{
							return true;
						}
					}
				}],

	        buttons:[{ 
	                text:'Speichern',
	                formBind: true,	 
	                handler:function(){ 
						if(Ext.getCmp('passwordResetForm').getForm().isValid()){

							// Ext.getCmp('passwordFieldNS').setRawValue(Ext.getCmp('passwordFieldNS').getValue());
							
							var newPassword = Ext.getCmp('passwordFieldNS').getValue();
							
							
							Ext.Ajax.request({
								method:'POST',
								url: cfg_backend_url +'User/ChangePassword', //... die korrekte URL
		                        waitTitle:'Verbindungsaufbau', 
		                        waitMsg:'Daten werden gesendet...',
								params:{
									password:newPassword
								},
								success:function(){ 
									rcm.Application.loadCombostores();
									passwordWindow.destroy();
		                        }
								
							});
							
							
						}
		
	                } 
	            }]
	    })
		
	}); 
	

	
	// Create a variable to hold our EXT Form Panel. 
	// Assign various config options as seen.	 
    var login = new Ext.FormPanel({ 
        labelWidth:120,
        url: cfg_backend_url +'User/Login', //... die korrekte URL
        frame:true, 
        title:'Benutzeranmeldung', 
        defaultType:'textfield',
		monitorValid:true,
		monitorResize:true,
		
	// Specific attributes for the text fields for username / password. 
	// The "name" attribute defines the name of variables sent to the server.
        items:[{ 
                fieldLabel:'Benutzername', 
                name:'username', 
                allowBlank:false ,
				width:200,
				id:'userNameInput'
            },{ 
                fieldLabel:'Passwort', 
                name:'password', 
                inputType:'password', 
				id:'passwordField',
                allowBlank:false ,
				width:200
            }],

        buttons:[{ 
                text:'Login',
                formBind: true,	 

                handler:function(){ 
					Ext.getCmp('passwordField').setRawValue(Ext.getCmp('passwordField').getValue());
                    login.getForm().submit({ 
                        method:'POST', 
                        waitTitle:'Verbindungsaufbau', 
                        waitMsg:'Daten werden gesendet...',
                        success:function(form, action){ 

							var user = Ext.util.JSON.decode(action.response.responseText);
							// console.log('result',result);
							
							
							if(user.loggedIn){
								
								// State Variablen setzen
								rcm.Application.state.user = user;
								rcm.Application.state.user.loggedIn = true;
								
								
								loginWindow.destroy();											
									
								if(user.passwort_neu_setzen){
									passwordWindow.show();
								}else{
									rcm.Application.loadCombostores();
								}
								
							}else{
								Ext.MessageBox.alert('Fehler','Das eingegebene Passwort ist nicht korrekt');
								Ext.getCmp('passwordField').setValue('');
							}
																


                        },

                        failure:function(form, action){ 
							if(action.failureType == 'server'){ 
                                obj = Ext.util.JSON.decode(action.response.responseText); 
                                Ext.Msg.alert('Login fehlgeschlagen!', obj.errors.reason); 
                            }else{ 
                                Ext.Msg.alert('Warnung!', 'Der Server ist nich erreichbar. : ' + action.response.responseText); 
                            } 
                            login.getForm().reset(); 
                        } 
                    }); 
                } 
            }]
    });

	

	// hier wir login in ein window gesteckt      
    var loginWindow = new Ext.Window({
        layout:'fit',
        width:350,
        height:150,
		y:100,
        closable: false,
        resizable: false,
        plain: true,
        border: false,
		modal: true,
        items: [login]
	});

	// loginWindow.show();






	
	
	// Privileged methods. Can be called from outside
    return {
		// public properties
	
		// Here comes the initialisation code
        init : function(){             

        },

		readCookie:function(name) 
		{
			// console.log(document.cookie);
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) {
					var value = c.substring(nameEQ.length,c.length);
					
					while(value.indexOf('+')!=-1){
						value = value.replace('+',' ');
					}
					
					return  unescape(value);		
				}

			}
			return null;
		},
		
		
		setCookie:function(name, wert, domain, expires, path, secure){
		   var cook = name + "=" + unescape(wert);
		   cook += (domain) ? "; domain=" + domain : "";
		   cook += (expires) ? "; expires=" + expires : "";
		   cook += (path) ? "; path=" + path : "";

		   cook += (secure) ? "; secure" : "";
		   document.cookie = cook;
		},
		

        

		showLoginForm : function(){ 
			loginWindow.show();
			
			var task = new Ext.util.DelayedTask();
			task.delay(100,function(){

				Ext.getCmp('userNameInput').focus();
				Ext.getCmp('userNameInput').clearInvalid();
			});
			
        },


        

		isLoggedIn : function(){
			
			var voller_name = this.readCookie('voller_name');
			var id = this.readCookie('id');
			var berechtigungsstufe = this.readCookie('berechtigungsstufe');
			
			if(id != null){
				rcm.Application.state.user.id = id;
				rcm.Application.state.user.loggedIn = true;
				rcm.Application.state.user.voller_name = voller_name;
				rcm.Application.state.user.berechtigungsstufe = berechtigungsstufe;

				return true;
			}else{
				return false;
			}
			
        }


    };
}();

