var SessionUpdate = Class.create({

    notificationTimerId : null, 
    periodicalExecuter: null,

   	initialize: function() {
        this.periodicalExecuter = new PeriodicalExecuter(this.restoreSession.bind(this), 3000);
    },
    
    restoreSession : function() {
    	
    	new Ajax.Request('/ajax/SessionUpdater/restoreSession', {
			method: 'post',
			onSuccess: function(x) {
				aHO.requestSuccess(x, 'loginMessage', null, null, { showSuccessMessage : false, showErrorMessage : false});
			},
			onFailure: function(x) {
				aHO.onFailure('loginMessage');
			}
		});
    },
    
	login: function(performAfterLogin) {

        // Die periodische Ausfuehrung der Datenaktualisierung stoppen
        //this.periodicalExecuter.stop();
		var self = this;
		
		new Ajax.Request('/ajax/SessionUpdater/doLogin', {
			method: 'post',
			parameters: {username: $F('loginUser'), password: MD5($F('loginPasswd'))},
			onSuccess: function(x) {
				
				aHO.requestSuccess(x, 'loginMessage', function (username, html) {
					
					/*self.adaptaPageToLoginStatus.apply(self, new Array(true));
					$('loggedInHeader').update(html);
					$('loggedInHeader').show();*/
					
					window.location.reload();
				
				}, null, { showSuccessMessage : false});
			},
			onFailure: function(x) {
				aHO.onFailure('loginMessage');
			}
		});

	},
	
    logout: function() {
		var self = this;
		
		new Ajax.Request('/ajax/SessionUpdater/doLogout', {
			method: 'post',
			onSuccess: function(x) {
				aHO.requestSuccess(x, 'loginMessage', function() {
					window.location.href = '/';
				}, null, { showSuccessMessage : false});
		},
			onFailure: function(x) {
				window.location.href='/';
			}
		});
    },
	
	/*adaptaPageToLoginStatus: function(isLoggedIn) {

		if(isLoggedIn == false) {
	        $('ajaxLoginForm').style.display = '';
	        $('loggedInHeader').hide();
	        $('loginLogoutButton').hide();
	        $('loginRegButton').style.display = '';
		} else {
	        $('ajaxLoginForm').hide();
	        $('loggedInHeader').style.display = '';
	        $('loginLogoutButton').style.display = '';
	        $('loginRegButton').hide();		
		}
	
	},*/
	
	loginThroughRegLogin: function(callAfterLogin, callingArguments) {
		 try {
			 // Alte Fehlermeldung(en) entfernen
			 $$('#regLogin .error').each(Element.remove);

			 var self = this;
			new Ajax.Request('/ajax/SessionUpdater/doLogin', {
				method: 'post',
				parameters: {username: $F('regLoginUser'), password: hex_sha1($F('regLoginPasswd'))},
				onSuccess: function(x) {
					aHO.requestSuccess(x, 'loginFormError', function() {
						currentOverlay.hide();
						self.adaptaPageToLoginStatus.apply(self, new Array(true));					
						callAfterLogin.apply(this, callingArguments);
	
					}, null, { showSuccessMessage : false});
				}.bind(this),
				onFailure: function(x) {
					this.loginThroughRegLoginFailure;
				}
			});
		} catch(e) {
			alert(e);
		}
	},

	getSessionData: function() {
	
		new Ajax.Request('/ajax/SessionUpdater/getNotificationsLink', {
			method: 'post',
			onSuccess: function(x) {
				aHO.requestSuccess(x, '', function(html) {
					$('notificationsCountContainer').update(html);
				}, null, { showSuccessMessage : false, showErrorMessage : false});
			}.bind(this),
			onFailure: function(x) {
				this.loginThroughRegLoginFailure;
			}
		});
	},
  
    processSessionData: function(ajaxResponse) {    
        
        return;
        
		var localData = (ajaxResponse != undefined) ? ajaxResponse['text'] : this.jsonResponse;

		// Progress-Anzeige ausblenden
		this.adaptProgress(((!localData['userid']) ? 'offlineBar' : 'onlineBar'), false);

		// Anzeige, wie viele Leute gerade online sind aktualisieren
		$('online_user').innerHTML = localData['onlineUserCount'] + ' Leute jetzt online!';
		
		// Wenn im Response keine userID enthalten ist, ist der User nicht
		// eigenloggt, es werden nur die allgemeinen Daten aktualisiert
        if (!localData['userid']) {
            this.adaptBarsToLoginStatus(false);
			if(this.periodicalExecuter) {
			  this.periodicalExecuter.stop();
			}
			return;
		}
		
		// Der User ist eingeloggt, also gesamte Leiste aktualisieren
        this.adaptBarsToLoginStatus(true);

        // Botschafen aus dem Response auslesen
        if (localData['botschaften']) {
        
            // Es gibt neue Botschaften, also also das Bild anpassen
            $('kosmosNavBotschaftenLink').removeClassName('botschaften');
            $('kosmosNavBotschaftenLink').addClassName('botschaften-a');
            
            // Wert fuer neue Botschaften setzen
            $('kosmosNavBotschaftenLink').innerHTML = localData['botschaften'];

        // Es gibt keine neuen Botschaften
        } else {
            $('kosmosNavBotschaftenLink').addClassName('botschaften');
            $('kosmosNavBotschaftenLink').removeClassName('botschaften-a');
        }
      
        // Abos aus dem Response auslesen
        if (localData['aboeintraege']) {
        
            // Es gibt aktuelle Abos, also Bild aktualisieren
            $('kosmosNavAbosLink').removeClassName('abos');
            $('kosmosNavAbosLink').addClassName('abos-a');
            
            // Wert fuer neue Botschaften setzen
            $('kosmosNavAbosLink').innerHTML = localData['aboeintraege'];

		} else {
            $('kosmosNavAbosLink').addClassName('abos');
            $('kosmosNavAbosLink').removeClassName('abos-a');
		}
    
		// Notifications auslesen  
		var notificationcnt = localData['notification'].length;

		// Alle Eintraege aus der Notifications-Liste loeschen
		$('notificationsList').innerHTML = '';

        // Es gibt keine Notifications, also die gesamte Leiste ausblenden
		if(notificationcnt == 0) {   
		   $('notificationContainer').style.display = "none";
		   return;
		}
        
        // Es sind Notifications vorhanden
        // Die Titelleiste anpassen, in der steht, wie viele Notifications vorhanden sind
        $('toggleNotifications').innerHTML = 'Du hast ' + notificationcnt + ' Nachricht' + ((notificationcnt == 1) ? '' : 'en');
        
        // Alle Notifications auslesen und als li in die ul einbauen
        localData['notification'].each(function(e) {
        
            var tmpLink = new Element('a', { href: e.url }).update(((e.message == '' || e.message == undefined) ? e.title : e.message));
            Event.observe(tmpLink, 'click', this.deleteNotificationAndGoto.bind(this, e.id, e.url));

            var avatarImg = new Element('img', {src: 'http://jetztimg.sueddeutsche.de/upl/images/user/' + getUserImagePath(e.sender) + '/thumbs_avatar/' + e.bildid + '.' + e.bildtyp});
        
            var delLink = new Element('a', { href: 'javascript:void(0);' }).update('Löschen');
            delLink.addClassName('deleteNotification');
            Event.observe(delLink, 'click', this.deleteNotification.bind(this, e.id));
        
            liEl = new Element('li', { id: "notification_" + e.id });

            liEl.appendChild(avatarImg);
            liEl.appendChild(tmpLink);
            liEl.appendChild(delLink);
            $('notificationsList').appendChild(liEl);      
        }.bind(this));
        
        $('notificationContainer').style.display = '';
       
        // Wenn es neue Nachrichten gibt, die Anzeige highlighten
        if (this.countNotifications != notificationcnt) {
            new Effect.Highlight('toggleNotifications', { startcolor: '#FFCDC6', endcolor: '#E85541', restorecolor: '#E85541'});
		}
		
		// Neuen Wert fuer den Notifications-Count speichern
		this.countNotifications = notificationcnt;

    },
    
    deleteNotification: function(id) {
        if(!confirm("Willst Du diese Nachricht wirklich löschen?"))
            return;
		
		new Ajax.Request('/ajax/SessionUpdater/deleteNotification', {
			method: 'post',
			parameters: {'id' : id},
			onSuccess: function(x) {
				aHO.requestSuccess(x, 'modal', function(id) {
					
					$('notification_' + id).remove();
					if($('sidebar_mynotificationsList').select('li').length == 0) {
						$('sidebar_mynotifications').remove();
					}
					
				}, null, { showSuccessMessage : false});
			}.bind(this),
			onFailure: function(x) {
				this.loginThroughRegLoginFailure;
			}
		});
    }
    
});

sessionUpdate = new SessionUpdate();
