/**
 * User Management - signup, login 
 *
 * Copyright: (c)2007 CK Web Technologies
 * Author:    Chris Knowles <chris.knowles@ckweb.com.au>
 * Version:   $Id: User.js 22 2007-11-13 04:31:39Z Chris $
 */

var User = function(app)
{
    this.app = app;
    this.loggedIn = false;
    this.email = null;
    this.playlistName = null;
    this.html = $D.id('challenge');
    this.logoutButton = $D.id('logoutButton');
    this.loggingOut = false;
    this.preventHideChallenge = false;
    
    this.signup = function()
    {
        var self  = this;
        var form = $D.id('signupForm');
        if (!form.signupEmail.value || !form.signupPassword.value || !form.signupChkPassword.value) {
            alert("You must enter all fields except playlist name");
            return false;
        }
        if (form.signupPassword.value != form.signupChkPassword.value) {
            alert("Passwords do not match, please try again");
            return false;
        }
        var http = new $H;
        http.post('signup/', 'email=' + form.signupEmail.value + '&password=' + form.signupPassword.value + '&name=' + form.playlistName.value, function(){self.finishSignup(http)});
        return true;
    };
    
    this.sendPassword = function()
    {
        var form = $D.id('forgottenPasswordForm');
        if (!form.loginEmail.value) {
           alert("Please enter an email address");
        } else {
            var http = new $H;
            var self = this;
            http.get('send_password/' + form.loginEmail.value + '/', false, function(){self.finishSendPassword(http)});
            this.tmp = $D.getContent(form);
            this.tmpEmail = form.loginEmail.value;
            $D.setContent(form, "Bitte warten...");
            return true;
        }
    };
    
    this.finishSendPassword = function(http)
    {
        if (http.text == '1') {
            $D.setContent('forgottenPasswordForm', "<p>Es gab ein Problem mit dem System. <a href='send_password/' id='pwdLink'>Bitte versuchen Sie es noch einmal</a></p>");
            var self  = this;
            this.preventHideChallenge = true;
            $E.listen('pwdLink', 'click', function(e){$E.kill(e);self.showChallenge("forgottenPassword")});
            
        } else if (http.text == '2') {
            $D.setContent('forgottenPasswordForm', this.tmp);
            var form = $D.id('forgottenPasswordForm');
            form.loginEmail.value = this.tmpEmail;
            this.tmp = "";
            var self = this;
            $E.listen('pwdButton', 'click', function(){self.sendPassword()});
            $E.listen('loginLink', 'click', function(e)
                {
                    $E.kill(e);
                    self.preventHideChallenge = true;
                    self.showChallenge("login");
                }
            );
            alert("The email address is not in our system. Please check it.");
        
        } else if (http.text == '3') {
            $D.setContent('forgottenPasswordForm', "<p>Ihr Passwort wurde an Ihre Email Adresse versand. Bitte überprüfen Sie Ihr Postfach in ein paar Minuten.</p><p><a href='login/' id='loginLink'>Login &raquo;</a></p>");
            this.preventHideChallenge = true;
            var self  = this;
            $E.listen('loginLink', 'click', function(e){$E.kill(e);self.showChallenge("login")});
        }
    };

    this.finishSignup = function(http)
    {
        var data = http.text.split("|");
        if (data[0] == 'success') {
            this.loggedIn = true;
            this.activateLogoutButton();
            this.email = data[1];
            this.playlistName = data[2];
            $D.setContent('my_playlist', data[2]);
            this.app.Storage.save();
            this.hideChallenge();
            return true;
        } else if (data[1] == "exists") {
            alert("Unter dieser Email Adresse ist bereits eine Playliste gespeichert - Bitte benutzen Sie eine andere oder loggen Sie sich in diesen Account um die erste Playliste zu bearbeiten. Passwort vergessen? Einfach den Link auf dieser Seite folgen.");
        } else if (data[1] == "email") {
            alert("Diese Email Adresse ist ungültig - bitte überprüfen Sie Ihre Eingabe");
        }
        return false;
    };
    
    this.login = function()
    {
        var button = $D.id('loginButton');
        var self  = this;
        var form = $D.id('loginForm');
        if (form.loginEmail.value && form.loginPassword.value) {
            var http = new $H;
            http.post(
                'login/', 
                'email=' + form.loginEmail.value + '&password=' + form.loginPassword.value, 
                function(){self.finishLogin(http)}
            );
        } else {
            alert("Bitte geben Sie Email und Passwort ein");
        }
    }; 
    
    this.finishLogin = function(http)
    {
        if (http.text != 0) {
        
            // clear playlist
            if (this.app.Playlist.totalSongs == 0) {
                $D.setContent('playlist', '');
            }
            
            // get record parts
            var record = http.text.split("|||");
            
            // flag as logged in
            this.loggedIn = true;
            
            // set user
            this.email = record[0];
            
            // set logout button
            this.activateLogoutButton();
            
            // set playlist name
            $D.setContent('my_playlist', record[1]);
            
            // started new playlist
            if (this.app.Playlist.totalSongs > 0) {
                
                if (record[2].length > 0 || record[3].length > 0) {

                    this.preventHideChallenge = true;
                    this.showChallenge('confirmOverride');
                    
                    var self = this;
                    $E.listen('confirmOverride', 'click', 
                        function(e)
                        {
                            $E.kill(e);
                            var target = $E.getTarget(e);
                            if (target.id == 'savedList') {
                                self.handleDb(record);
                                
                            } else if (target.id == 'newList') {
                                self.app.Storage.clearDb(self.email);
                                self.preventHideChallenge = false;
                                self.hideChallenge();
                                self.app.Storage.setAutoSave();
                            }
                        }
                    );
                    return true;
                      
                }
             
            // not started new playlist   
            } else {
                // handle db
                this.handleDb(record); 
            }
            
            this.hideChallenge();
            
            // start auto saving
            this.app.Storage.setAutoSave();
            
            return true;
            
        } else {
            alert("Die Login Daten stimmen nicht - Bitte probieren Sie es noch einmal");
            http.cancel();
            
        }
        return false;
    };
    
    this.handleDb = function(record)
    {
        // both tracks and autosave
        if (record[2] && record[3]) {
        
            this.preventHideChallenge = true;
            this.showChallenge('exitedUnsaved');
            
            var self = this;
            $E.listen('exitedUnsaved', 'click', 
                function(e)
                {
                    $E.kill(e);
                    var target = $E.getTarget(e);
                    if (target.id == 'exitSavedList') {
                        self.app.Playlist.load(record[2]);
                        self.app.Storage.clearAutosave(self.email);
                        self.preventHideChallenge = false;
                        self.hideChallenge();
                                        
                    } else if (target.id == 'exitBackedUpList') {
                        self.app.Playlist.load(record[3]);
                        self.app.Playlist.setUnsaved();
                        self.app.Storage.save('force');
                        self.preventHideChallenge = false;
                        self.hideChallenge();
                        
                    }
                    self.app.Storage.setAutoSave();
                }
            );
            return false;
                    
            /*
              if (window.confirm("Sie haben bei Ihrem letzten Besuch nicht gespeichert. We have your last saved list and the list as it was when you exited. Do you want to use the list as it was when you exited?")) {
                this.app.Playlist.load(record[3]);
                this.app.Playlist.setUnsaved();
                this.app.Storage.save('force');
                
             } else {
                this.app.Playlist.load(record[2]);
                this.app.Storage.clearAutosave(this.email);
             }
              */
            
        // tracks only
        } else if (record[2]) {
            this.app.Playlist.saved = true;          
            this.app.Playlist.load(record[2]);
            
        // autosave only   
        } else if (record[3]) {
            this.app.Playlist.saved = true;
            this.app.Playlist.load(record[3]);
            this.app.Storage.save();
            
        }
        this.app.Storage.setAutoSave();
        this.preventHideChallenge = false;
        this.hideChallenge();

    };
           
    this.showChallenge = function(elements)
    {
        var self = this;
        
        // clear player content
        //$D.id('player').style.visibility = 'hidden';
        //$D.id('player').style.zIndex = '-1';
        //$D.setContent($D.id('player-artist'), "");
        //$D.setContent($D.id('player-title'), "");
        
        // load interface
        if (elements == 'all') {
            this.html.innerHTML = this.app.Content.all;
        } else if (elements == 'login') {
            this.html.innerHTML = this.app.Content.loginOnly;
        } else if (elements == 'confirmOverride') {
            this.html.innerHTML = this.app.Content.confirmOverride;
        } else if (elements == 'exitedUnsaved') {
            this.html.innerHTML = this.app.Content.exitedUnsaved;
        } else if (elements == 'logoutSave') {
            this.html.innerHTML = this.app.Content.logoutSave;
        } else if (elements == 'forgottenPassword') {
            this.html.innerHTML = this.app.Content.forgottenPassword;
        }
        
        // show the user panel
        if (!this.preventHideChallenge) {
            $F.fadeIn(this.html);
        }
        
        // listen for save later button click
        $E.listen('saveLater', 'click', function(){self.preventHideChallenge = false;self.hideChallenge()});
        
        // listen for signup button click
        $E.listen('signupButton', 'click', function(){self.signup()});
        
        // listen for login button click
        $E.listen('loginButton', 'click', function(){self.login()});
        
        // listen for forgotten password button click
        $E.listen('pwdButton', 'click', function(){self.sendPassword()});
        $E.listen('pwdLink', 'click', function(e)
            {
                $E.kill(e);
                self.preventHideChallenge = true;
                self.showChallenge("forgottenPassword");
            }
        );
        $E.listen('loginLink', 'click', function(e)
            {
                $E.kill(e);
                self.preventHideChallenge = true;
                self.showChallenge("login");
            }
        );
        
        //this.preventHideChallenge = false;
        
    };
    
    this.hideChallenge = function()
    {
        if (!this.preventHideChallenge) {
            //$D.id('player').style.visibility = 'visible';
            $F.fadeOut(this.html);
        }
    };
    
    this.activateLogoutButton = function()
    {
        this.logoutButton.className = 'unsaved';
        var self = this;
        $E.listen(this.logoutButton, 'click', function(){self.logout()});
    };

    this.deactivateLogoutButton = function()
    {
        this.logoutButton.className = 'saved';
        var self = this;
        $E.ignore(this.logoutButton, 'click', function(){self.logout()});
    };

    this.logout = function()
    { 
        if (!this.app.Playlist.saved) {
        
            this.showChallenge('logoutSave');
            
            var self = this;
            $E.listen('logoutSave', 'click', 
                function(e)
                {
                    $E.kill(e);
                    var target = $E.getTarget(e);
                    if (target.id == 'saveList') {
                        self.app.Storage.save('logout');
                                        
                    } else if (target.id == 'ignoreList') {
                        self.finishLogout();
                        
                    }
                }
            );
            return false;
            
        } else {
            this.exit();
        }
    };
    
    this.finishLogout = function()
    {
        this.loggingOut = true;
        var http = new $H;
        var self = this;
        http.post('clear_autosave/', 'user=' + this.email, function(){self.exit(http)});
    };
    
    this.exit = function(http)
    {
        window.location = "/";
    };
    
}

