/*
 * Copyright 2006 OST-SYSTEMS. All rights reserved.
 */

function Login(loadingIcon, afterLoginCallback, errorCallback) {
  this.storage = null;
  this.loadingIcon = loadingIcon;
  this.afterLoginCallback = afterLoginCallback;
  this.errorCallback = errorCallback;
  this.cookie = new Cookie("Login");
  this.persist = false;
  this.user = null;
  this.password = null;
  this.keepAliveTicket = null;
  
  var createServerStorage = function(_self, callback) {
    var path = location.pathname;
    var index = path.lastIndexOf('/');
    if (index >= 0) {
      path = path.substring(0, index);
    }
    return new ServerStorage(path + "/commands", callback, _self.loadingIcon);    
  }
  
  this.loginCallback = function(status) {
    if (status == "login") {
      keyStorage = this.storage;
      this.loginDone();
      //reloadWidgets();
      if (this.persist) {
        var value = "['" + this.user + "','" + this.password + "']";
        this.cookie.store(value);
      }
      else {
        this.cookie.remove();
      }
      this.startKeepAlive();
      afterLoginCallback(true);  
    }
    else if (status == "loginFailed") {
      alert("Login failed.");
      this.stopKeepAlive();
      afterLoginCallback(false);  
    }
    else if (status == "newUser") {
      this.storage.setStorage(keyStorage.getStorage());
      keyStorage = this.storage;
      this.storage.sendAll();
      this.loginDone();
      //reloadWidgets();
      if (this.persist) {
        var value = "['" + user + "','" + password + "']";
        this.cookie.store(value);
      }
      else {
        this.cookie.remove();
      }  
      this.startKeepAlive();
      afterLoginCallback(true);  
    }
    else if (status == "newUserFailed") {
      alert("Creating new user failed.");
      this.stopKeepAlive();
      afterLoginCallback(false);  
    }
    else if (status == "noLogin") {
      alert("Please login first.");
      /*
      this.logoutDone();
      this.stopKeepAlive();
      afterLoginCallback(false);
      */
      location.reload(true);  
    }
    else if (status == "oldTicket") {
      alert("Your session has expired, please login.");
      /*
      this.logoutDone();
      this.stopKeepAlive();
      afterLoginCallback(false);
      */
      location.reload(true);  
    }
  }

  this.login = function(user, password, persist) {
    var _self = this;
    this.storage = createServerStorage(this, function(status) {
      _self.loginCallback(status);
    });
    this.persist = persist;
    this.user = user;
    this.password = password;
    this.storage.login(user, password);
  }  
  
  this.logout = function() {
    this.stopKeepAlive();
    this.storage.logout();
    this.logoutStorage();
  }  
    
  this.logoutStorage = function() {  
    keyStorage = new StorageClass();
    keyStorage.setStorage(this.storage.getStorage());
    this.storage = keyStorage;
    this.cookie.remove();
  }
  
  this.createNewUser = function(user, password, persist) {
    var _self = this;
    this.storage = createServerStorage(this, function(status) {
      _self.loginCallback(status);
    });
    this.storage.newUser(user, password);
  }  
  
  this.removeUser = function() {
    if (confirm("Really remove your account and all your widgets settings?")) {
      this.storage.removeUser();
      this.logoutStorage();
    }  
  }
  
  this.checkAutoLogin = function() {
    var params = new Object();
    var _self = this;
    doRequest(params, "checkAlive", function(request) {
      if (request.status == 200) {
        var status = eval(request.responseText);
        if (!status || status != 'success') {
          var details = _self.cookie.get();
          if (details != null) {
            details = eval(details);
            _self.login(details[0], details[1], true);
          }
          else {
            _self.stopKeepAlive();
            afterLoginCallback(false);
          }
        }
        else {
          _self.storage = createServerStorage(_self, function(status) {
            _self.loginCallback(status);
          });
          //self.loginCallback("login");
          _self.storage._loginOnLoad(_self.storage, request);
          var details = _self.cookie.get();
          if (details != null) {
            details = eval(details);
            _self.user = details[0];
            _self.password = details[1];
            _self.persist = true;
            document.getElementById("ChangeName").value = _self.user;
          }          
        }  
      }
      else {
        var details = _self.cookie.get();
        if (details != null) {
          details = eval(details);
          _self.login(details[0], details[1], true);
        }
        else {
          _self.stopKeepAlive();
          afterLoginCallback(false);
        }
      }
    }, "WidgetsLoading");
  }

  this.showLogin = function() {
    openPopout("LoginSection");
  }
  
  this.showNewUser = function() {
    openPopout("NewUserSection");
  }
  
  this.closeLogin = function() {
    closePopout();
  }
  
  this.doLogin = function() {
    var name = document.getElementById("LoginName").value;
    var password = document.getElementById("LoginPassword").value;
    var persistent = document.getElementById("LoginKeep").checked;  
    if (name == null || name.length < 1) {
      alert("Name is missing.");
      return false;
    }
    if (password == null || password.length < 1) {
      alert("Password is missing.");
      return false;
    }
    document.getElementById("LoginPassword").value = null;
    if (!loginObj) {
      loginObj = new Login(document.getElementById("WidgetsLoading"));
    }
    loginObj.login(name, password, persistent);
    this.closeLogin();
    return true;
  }
  
  this.loginDone = function() {
    loginDone(this.user);
  }
  
  this.newUser = function() {
    var name = document.getElementById("NewUserName").value;
    var password = document.getElementById("NewUserPassword").value;
    var password2 = document.getElementById("NewUserPassword2").value;
    if (name == null || name.length < 6) {
      alert("Name is too short.");
      return false;
    }
    if (name.length > 120) {
      alert("Name is too long (maximum 120 characters).");
      return false;
    }
    if (password == null || password.length < 6) {
      alert("Password is too short.");
      return false;
    }
    if (password2 == null || password != password2) {
      alert("Password is not the same.");
      return false;
    }
    if (password.length > 20) {
      alert("Password is too long (maximum 20 characters).");
      return false;
    }
    document.getElementById("NewUserPassword").value = null;
    document.getElementById("NewUserPassword2").value = null;
    if (loginObj == null) {
      loginObj = new Login(document.getElementById("WidgetsLoading"));
    }  
    loginObj.createNewUser(name, password);
    this.closeLogin();
    return true;
  }
  
  this.logoutDone = function() {
    logoutDone();
  }
  
  this.doLogout = function() {
    this.logoutDone();
    this.logout();
  }
  
  this.doRemoveUser = function() {
    this.logoutDone();
    this.removeUser();
  }
  
  this.startKeepAlive = function() {
    this.stopKeepAlive();
    var _self = this;
    this.keepAliveTicket = setInterval(function() {
      var params = new Object();
      doRequest(params, "checkAlive", function(request) {
        if (request.status == 200) {
          var status = eval(request.responseText);
          if (status != 'success') {
            _self.stopKeepAlive();
          }
          _self.loginCallback(status);
        }
      });
    }, 1000 * 60 * 10);
  }
    
  this.stopKeepAlive = function() {
    if (this.keepAliveTicket != null) {
      clearInterval(this.keepAliveTicket);
    }
  }
  
  this.changeUserName = function() {
    var value = document.getElementById("ChangeName").value;
    var _self = this;
    if (value != null && value.length >= 6) {
      var params = new Object();
      params.name = value;
      if (!_self.password) {
        _self.password = prompt("Please enter the password:", "");
      }
      params.password = _self.password;
      _self.newName = value;
      doRequest(params, "changeUserName", function(request) {
        if (request.status == 200) {
          var errorMessage = null;
          var status = eval(request.responseText);
          if (status == "success" && !errorMessage) {
            _self.user = _self.newName;
            if (_self.persist) {
              var value = "['" + _self.user + "','" + _self.password + "']";
              _self.cookie.store(value);
            }
            alert("Rename successful.");
            closePopout();
          }
          else {
            var msg = status;
            if (errorMessage) {
              msg = errorMessage;
            }
            alert("Change failed: " + msg);
          } 
        }
      }, "ControlsLoading");
    }
    else {
      alert("New name ist too short.");
    }
  }

  this.changePassword = function() {
    var value1 = document.getElementById("ChangePassword").value;
    var value2 = document.getElementById("ChangePassword2").value;
    var _self = this;
    if (value1 == value2) {
      if (value1 != null && value1.length >= 6) {
        document.getElementById("ChangePassword").value = null;
        document.getElementById("ChangePassword2").value = null;
        var params = new Object();
        params.newPassword = value1;
        if (!_self.password) {
          _self.password = prompt("Please enter the password:", "");
        }
        params.password = _self.password;
        _self.newPassword = value1;
        doRequest(params, "changePassword", function(request) {
          if (request.status == 200) {
            var errorMessage = null;
            var status = eval(request.responseText);
            if (status == "success" && !errorMessage) {
              _self.password = _self.newPassword;
              if (_self.persist) {
                var value = "['" + _self.user + "','" + _self.password + "']";
                _self.cookie.store(value);
              }
              alert("Password change successful.");
              closePopout();
            }
            else {
              var msg = status;
              if (errorMessage) {
                msg = errorMessage;
              }
              alert("Change failed: " + msg);
            } 
          }
        }, "ControlsLoading");
      }
      else {
        alert("New password ist too short.");
      }
    }
    else {
      alert("Passwords are different");  
    }
  }
}


