var MagmaLicense = null;
var LICENSE = {
  LOGOFFBEFORE: "license:logoffbefore",
  LOGOFFERROR: "license:logofferror",
  PASSWORDUPDATED: "license:passwordupdated",
  PASSWORDUPDATEERROR: "license:passwordupdateerror",
  PASSWORDUPDATEDISABLED: "license:passwordupdatedisabled",
  LICENSEVALUESUPDATED: "license:valuesupdated",    
  LOGINSHOW: "login:show",
  LOGINHIDE: "login:hide",
  LOGINSUBMIT: "login:submit",  
  LOGINMESSAGE: "login:message",
  LOGINENABLED: "login:enabled",
  LOGINDISABLED: "login:disabled"  
}

// Start of KMMPRecoverPassword component
var KMMPRecoverPassword = {
  majorversion: function() {
    return 1;
  },
  
  minorversion: function() {
    return 2;
  },
    
  _construct: function() {
    this._url = null;
    this._initialized = false;    
  },  	
		
	onFailure: null,	
	onSuccess: null,
	
  initialize: function(url) {
    if (!this._initialized) {
      if ((url == null) || (url == "")) {      	
      	return false;
      } else {
        this._url = url;        
        this._initialized = true;
        return true;
      }
    } else {
      return true; 
    }
  },
    
  initialized: function() {
    return this._initialized;
  },
   
  recover: function(userId, onSuccess, onFailure, settingsId)
	{							
		if ((this._initialized) && (userId != null)) {					  
		 	try {
		 	  KMMPRecoverPassword.onSuccess = onSuccess;
		 	  KMMPRecoverPassword.onFailure = onFailure;
		 	  if ((settingsId == null) || (typeof settingsId != "string")) {
		 	    settingsId = ""; 
		 	  }
		 	  
		 	  var list = new Hash({ userid: userId, 
		 	    kmmagmaplatformrequesttype: "ajaxpasswordrequest",
		 	    emailsettingsid: settingsId });												  	 	   	
				
		    new Ajax.Request(this._url,
		    {
			    method: 'get',
			  	parameters: list.toQueryString(),
			  	onSuccess: function(transport) {				  		
					  var json = transport.responseText.evalJSON(true);								
						if ((json.PasswordRequest) && (json.PasswordRequest.Error)) {							
							if (KMMPRecoverPassword.onFailure) {
			    	    KMMPRecoverPassword.onFailure(json);
			    	  }
						}	else {
							if (KMMPRecoverPassword.onSuccess) {
			    	    KMMPRecoverPassword.onSuccess(json);
			    	  }						  
						}					
			  	},
			    onFailure: function() {			  	  				    	
			    	if (KMMPRecoverPassword.onFailure) {
			    	  KMMPRecoverPassword.onFailure(null);
			    	}
				  }
				});			
		  } catch(err) {		    
		    if (KMMPRecoverPassword.onFailure) {
			    KMMPRecoverPassword.onFailure(null);
			  }
		  }
		} else if (onFailure) {
		  onFailure(null); 
		} 
	}  	
}
KMMPRecoverPassword._construct();
// End of KMMPRecoverPassword component

Event.observe(window, "load", OnInitializeLicenseConstants);

function OnInitializeLicenseConstants()
{
  if ((self.MAGMA) && (MAGMA.EVENT)) {
    MAGMA.EVENT.LICENSE = LICENSE;
  }  
}

function KMMagmaLicenseLoader(loginOptions)
{
  _Create(loginOptions);
  
  function _Create(loginOptions)
  {      
    if ((self.LicenseValues) && (LicenseValues.License != null)) {
      var startupinfo = {}
      if ((self.__StartupInfo) && (__StartupInfo.LoggedIn === true)) {
        startupinfo = self.__StartupInfo;
      }
      
      _StartApplication(startupinfo);
    } else {
      new KMMagmaLicenseLoginUI(loginOptions, _StartApplication);
    }    
  }
  
  function _StartApplication(startInfo)
  {       
    document.fire(MAGMA.EVENT.APPLICATION.STARTINFOAVAILABLE, startInfo);    
    MagmaLicense = new KMMagmaLicense();    
    document.fire(MAGMA.EVENT.APPLICATION.PRELOADAUTHORIZED);    
    document.fire(MAGMA.EVENT.APPLICATION.LOADAUTHORIZED);    
  }
}

function KMMagmaLicenseLoginUI(options, startApplication)
{
  var _options = options;
  var _startApplication = startApplication;
  var _loginInProgress = false;
  var _loginEnabled = true;
  
  this.SetLoginStatus = _SetLoginStatus;
  
  _Create();
  
  function _Create()
  {    
    if (_options) {
      for (var key in _options) {
        if (typeof _options[key] == "string") {          
          _options[key] = $(_options[key]);
        }
      }      
      
      if ((Object.isElement(_options.LoginPanel)) && 
          (Object.isElement(_options.IdField)) &&
          (Object.isElement(_options.PasswordField)) &&
          (Object.isElement(_options.LoginCommand)) &&
          (Object.isFunction(_startApplication))) {
        Event.observe(_options.LoginCommand, "click", _LogIn);      
        Event.observe(_options.IdField, "keypress", _OnLogInKeyPress);
        Event.observe(_options.PasswordField, "keypress", _OnLogInKeyPress);         
        Event.observe(_options.LoginCommand, "mouseover", _OnMouseOver);
        Event.observe(_options.LoginCommand, "mouseout", _OnMouseOut);  
          
        if(Object.isElement(_options.RememberField)) {
          Event.observe(_options.RememberField, "mouseover", _OnMouseOver);
          Event.observe(_options.RememberField, "mouseout", _OnMouseOut);          
        }
          
        if (self.KMMagmaHealth) {  
          Event.observe(document, HEALTH.SESSIONFAILURE, _OnSessionFailure);      
          Event.observe(document, HEALTH.NETWORKFAILURE, _OnSessionFailure);    
          Event.observe(document, HEALTH.PERMANENTNETWORKFAILURE, _OnSessionFailure);        
          Event.observe(document, HEALTH.SESSIONHEALTHY, _OnSessionHealthy);          
        }
        
        if (typeof _options.MessageDialog != "object") {
          _options.MessageDialog = new Knowmax.SimpleDialog.Add({Element: _options.MessagePanel});                        
        }    
        if (Object.isElement(_options.MessageCloseCommand)) {
          Event.observe(_options.MessageCloseCommand, "click", _OnCloseMessage);
        }        
        
        _InitializePasswordRecovery();
        
        document.fire(LICENSE.LOGINSHOW);
        Element.show(_options.LoginPanel);          
        _SetLoginStatus(true);
        _InitialFocus();
      } else {
        alert("Unable to initialize login ui.");
      }
    }
  }
  
  function _UpdateOverClass(element, overNode)
  {        
    if (Object.isElement(element)) {                 
      if (overNode) {
        Element.addClassName(element, "over");   
      } else {
        Element.removeClassName(element, "over");
      }
    }         
  }    
  
  function _OnMouseOver(event)
  {
    _UpdateOverClass(event.element(), true);
  }
  
  function _OnMouseOut(event)
  {
    _UpdateOverClass(event.element(), false);  
  }    
  
  function _OnSessionFailure()
  {
    _SetLoginStatus(false);
  }
  
  function _OnSessionHealthy()
  {
    _SetLoginStatus(true);
  }
  
  function _InitializePasswordRecovery()
  {
    if ((Object.isElement(_options.TogglePasswordRecoveryCommand)) &&
        (Object.isElement(_options.PasswordRecoveryPanel)) && 
        (Object.isElement(_options.RecoverIdField)) &&
        (Object.isElement(_options.RecoverCommand)))  {
      Event.observe(_options.TogglePasswordRecoveryCommand, "click", _OnTogglePasswordRecovery);
      Event.observe(_options.RecoverIdField, "keypress", _OnRecoverPasswordKeyPress);
      Event.observe(_options.RecoverCommand, "click", _RecoverPassword);        
      Event.observe(_options.TogglePasswordRecoveryCommand, "mouseover", _OnMouseOver);
      Event.observe(_options.TogglePasswordRecoveryCommand, "mouseout", _OnMouseOut); 
      if (_options.CancelRecoverCommand) {
        Event.observe(_options.CancelRecoverCommand, "click", _OnCancelRecover)
      }        

      if ((self.Knowmax) && (self.Knowmax.SimpleDialog)) {
        _options.PasswordRecoveryDialog = new Knowmax.SimpleDialog.Add({Element: _options.PasswordRecoveryPanel,
            Modal: true});
      } else {
        _options.PasswordRecoveryDialog = null;
      }
    }  
  }   
  
  function _RecoverPassword()
  {          
    if (self.KMMPRecoverPassword) {    
      var id = _GetTextValue(_options.RecoverIdField);      
      if ((id != null) && (id != "") &&  
          (KMMPRecoverPassword.initialize(Values.Application.Module))) {        
        KMMPRecoverPassword.recover(id, _OnPasswordRetrieved, _OnPasswordFailure); 
      }
    }  
  }
  
  function _OnPasswordRetrieved(response)
  {
    var text;
    if ((!self.LicenseLanguage) || (!LicenseLanguage.PasswordRecoverSuccess)) {
      text = "Password recovered.";
    } else {
      text = LicenseLanguage.PasswordRecoverSuccess;    
    }
    
    _ShowMessage(text, false);
    _SetTextValue(_options.RecoverIdField, null);
    _HidePasswordRecovery();    
  }
   
  function _OnPasswordFailure(response)
  {
    var text;
    if ((!self.LicenseLanguage) || (!LicenseLanguage.PasswordRecoverFailed)) {
      text = "Unable to recover password.";    
    } else {
      text = LicenseLanguage.PasswordRecoverFailed;    
    }
    
    _ShowMessage(text, true);
  }  
  
  function _OnTogglePasswordRecovery()
  {    
    if (_options.PasswordRecoveryPanel.getAttribute("status") == "show") {
      _HidePasswordRecovery()
    } else {
      _ShowPasswordRecovery();	
    }     
  }
  
  function _OnCancelRecover()
  {
    _HidePasswordRecovery();
  }
  
  function _HidePasswordRecovery()
  {
    if (_options.PasswordRecoveryDialog) {
      _options.PasswordRecoveryDialog.Hide(_HidePasswordRecoveryDone);
    } else if (self.Effect) {
      Effect.Fade(_options.PasswordRecoveryPanel, {afterFinish: _HidePasswordRecoveryDone});
    } else {
      Element.hide(_options.PasswordRecoveryPanel);
      _HidePasswordRecoveryDone();
    }
  }
  
  function _ShowPasswordRecovery()
  {      
    if (_options.PasswordRecoveryDialog) {
      _options.PasswordRecoveryDialog.Show(_ShowPasswordRecoveryDone);
    } else if (self.Effect) {
      Effect.Appear(_options.PasswordRecoveryPanel, {afterFinish: _ShowPasswordRecoveryDone});
    } else {
      Element.show(_options.PasswordRecoveryPanel);
      _ShowPasswordRecoveryDone();
    } 
  }
  
  function _ShowPasswordRecoveryDone() 
  {
    _options.PasswordRecoveryPanel.setAttribute("status", "show");
    _SetTextValue(_options.RecoverIdField, _GetTextValue(_options.IdField));
    if (_options.RecoverIdField.focus) {
      try {
        _options.RecoverIdField.focus();
      } catch(ex) {
      }      
    }
  }
  
  function _HidePasswordRecoveryDone()
  {
    _options.PasswordRecoveryPanel.setAttribute("status", "hide");  
    _InitialFocus();
  }
  
  function _OnRecoverPasswordKeyPress(event)
  {
    if (event.keyCode == Event.KEY_RETURN) { 
      event.returnValue = false;
    	if (event.preventDefault) {
    		event.preventDefault();
    	}
  		try {			
  	  	event.keyCode = 0;
  		} catch(e) {
  		}  
      
      _RecoverPassword()
    }  
  }
  
  function _SetLoginStatus(enabled)
  {  
    if ((enabled != null) && (typeof enabled == "boolean")) {
      _loginEnabled = enabled;
      
      for (var key in _options) {
        if (Object.isElement(_options[key])) {   
          if (enabled === true) {        
            _options[key].disabled = "";          
          } else {
            _options[key].disabled = "disabled";
          }
        }
      }  
      
      if ((Object.isElement(_options.RememberField)) && (!document.cookie)) {
        _options.RememberField.disabled = "disabled";
      }
      
      if (enabled === true) {
        document.fire(LICENSE.LOGINENABLED);  
      } else {
        document.fire(LICENSE.LOGINDISABLED);  
      }            
    }
  }
  
  function _OnLogInKeyPress(event)
  {
    if (event.keyCode == Event.KEY_RETURN) { 
      event.returnValue = false;
    	if (event.preventDefault) {
    		event.preventDefault();
    	}
  		try {			
  	  	event.keyCode = 0;
  		} catch(e) {
  		}  
      
      _LogIn()
    }  
  }
  
  function _LogIn()
  {
    if ((!_loginInProgress) && (_loginEnabled)) {
      var id = _GetTextValue(_options.IdField);    
      var password = _GetTextValue(_options.PasswordField);
      if ((id !== "") && (password !== "")) {             
        _loginInProgress = true;
        document.fire(LICENSE.LOGINSUBMIT); 
        
        var autologon = false;
        if (Object.isElement(_options.RememberField)) {
          autologon = _options.RememberField.checked;          
        }
        
      	var list = new Hash({ "userid": id, "password": password, 
          "autologon": autologon, "kmmagmaplatformrequesttype": "login",
          "ajax": "true", "sid": Values.User.Sid });	
        	  
        try { 
        	new Ajax.Request(Values.Application.Module,
        	{
        	  method: 'get',
            evalJSON: true,
        		parameters: list.toQueryString(),
        		onSuccess: _LogInResult,			
        	  onFailure: function(value) {
              var text = "Unable to connect to server.";
              if ((value) && (value.responseText) && 
                  (typeof value.responseText == "string") && (value.responseText != "")) {
                text = value.responseText;
              } 
        	  	_LogInError(text);
        	  }
        	});		  
        } catch(ex) {
          _LogInError(ex.message);
        }      
      }    
    }
  }
  
  function _GetTextValue(field)
  {
    if (Object.isElement(field)) {
      if (field.GetValue) {
        return field.GetValue();
      } else {
        return field.value;
      }
    }
    return null;
  }
  
  function _SetTextValue(field, value)
  {
    if (Object.isElement(field)) {
      if ((value == null) || (Object.isUndefined(value))) {
        value = "";
      }    
      
      if (field.SetValue) {
        field.SetValue(value);
      } else {
        field.value = value;
      }
    }
  }
  
  function _LogInResult(result)
  {  
    if (result.responseJSON.LoggedIn) {             
      document.fire(LICENSE.LOGINHIDE, {CallBack: _startApplication, StartInfo: result.responseJSON});      
      if ((typeof _options.AutoStartApplication == "boolean") &&
          (_options.AutoStartApplication)) {
        Element.hide(_options.LoginPanel);
        _startApplication(result.responseJSON);    
      }
    } else {
      _LogInError(result.responseJSON.Text);
    }    
  }

  function _LogInError(text)
  {      
    _loginInProgress = false;
    _SetTextValue(_options.PasswordField, null);        
    _ShowMessage(text, true);
    _InitialFocus();     
  } 

  function _ShowMessage(text, isError)
  {
    if (text == null) {
      text = ""; 
    }

    document.fire(LICENSE.LOGINMESSAGE, {IsError: isError, Text: text});
    
    if (text !== "") {
      if ((typeof _options.MessageDialog == "object") &&
          (Object.isElement(_options.MessageField))) {
        _options.MessageField.innerHTML = unescape(text);
        _options.MessageDialog.Show();
      } else {
        alert(unescape(text));
      }    
    }
  } 
  
  function _OnCloseMessage()
  {
    if (typeof _options.MessageDialog == "object") {
      _options.MessageDialog.Hide();
    }
  }
  
  function _InitialFocus()
  {    
    if ((Object.isElement(_options.IdField)) && (_options.IdField.focus)) {
      try {
        _options.IdField.focus();
      } catch(ex) {
      }
    }
  }  
}

function KMMagmaLicensePasswordUI(oldField, newField, 
  confirmField, trigger, messageField)
{
  var _oldField = $(oldField);
  var _newField = $(newField);
  var _confirmField = $(confirmField);
  var _trigger = $(trigger);
  var _messageField = $(messageField); 
  
  _Initialize();
  
  function _Initialize() 
  {  
    if ((_oldField != null) && (_newField != null) &&
        (_confirmField != null) && (_trigger != null)) {                                    
      if ((Proxy.GetValues().Application.IsServer) && 
          (Proxy.GetContext().MagmaLicense.GetValues().License.PasswordUpdateAllowed)) {        
        Event.observe(_trigger, "click", _OnTriggerClick);
        Proxy.GetEventSink().observe(LICENSE.PASSWORDUPDATED, _OnPasswordUpdated);
        Proxy.GetEventSink().observe(LICENSE.PASSWORDUPDATEERROR, _OnPasswordUpdateError);
      } else {
        _DisableUpdatePassword();
      }
    }
  }
  
  function _DisableUpdatePassword()
  {
    _oldField.disabled = "disabled";
    _newField.disabled = "disabled";
    _confirmField.disabled = "disabled";
    _trigger.disabled = "disabled";  
    Proxy.GetEventSink().fire(LICENSE.PASSWORDUPDATEDISABLED); 
  }
  
  function _OnTriggerClick(event)
  {
    _trigger.disabled = "disabled";        
    Proxy.GetContext().MagmaLicense.UpdatePassword(
      _oldField.value, _newField.value, _confirmField.value);    
  }
  
  function _OnPasswordUpdated(event)
  {
    _UpdateMessageText(event.memo);
    _EndPasswordUpdate();    
  }
  
  function _OnPasswordUpdateError(event)
  {       
    _UpdateMessageText(event.memo);
    _EndPasswordUpdate();
  }
  
  function _EndPasswordUpdate()
  {
    _oldField.value = "";
    _newField.value = "";
    _confirmField.value = "";
    _trigger.disabled = "";  
  }
  
  function _UpdateMessageText(text)
  {    
    if (_messageField != null) {
      if (text == null) {
        text = "";
      }

      _messageField.innerHTML = unescape(text);
    }        
  }
}

function KMMagmaLicense()
{  
  var _lastError = "";
  var _abortLogOff = false;  
  
  this.LogOff = _logOff;
  this.LastError = _lastError;
  this.AbortLogOff = _abortLogOff;
  this.UpdatePassword = _updatePassword;
  this.UpdateValues = _updateValues;
  this.UpdateLicense = _updateLicense;
  this.UpdateDisplaySettings = _updateDisplaySettings;
  this.GetValues = _getValues;
  
  _create();
  function _create()
  {      
    _valuesReceived(Proxy.GetStartupInfo());    
  }
  
  function _getValues()
  {   
    var context = Proxy.GetContext();
    if ((context != null) && (context.LicenseValues)) {
      return context.LicenseValues;
    } else {
      return null;
    }      
  }
  
  function _updateDisplaySettings(options)
  {
    if (options != null) {
      if (!Object.isString(options.NoLicense)) {
        options.NoLicense = "";
      }
      if (!Object.isString(options.Disabled)) {
        options.Disabled = "";
      }
      
      var list = new Hash({ "sid": Proxy.GetValues().User.Sid,
        "nolicenseitemtype": options.NoLicense,
        "disableditemtype": options.Disabled,        
        "kmmagmaplatformrequesttype": "displaysettings"});	
        
      try { 
        new Ajax.Request(Proxy.GetValues().Application.Module,
        { method: 'post',
          evalJSON: true,
          parameters: list.toQueryString(),
          onSuccess: function(result) {                   
            _valuesReceived(result.responseJSON);
            //Proxy.GetEventSink().fire(LICENSE.LICENSEVALUESUPDATED); not needed since we reload application right after this             
            Proxy.Application.Reload();             
          }
        });		  
      } catch(ex) {        
      }       
    }
  }
  
  function _updateValues()
  {
    var list = new Hash({ "sid": Proxy.GetValues().User.Sid, 
      "kmmagmaplatformrequesttype": "licenseinfo"});	
    	  
    try { 
    	new Ajax.Request(Proxy.GetValues().Application.Module,
    	{ method: 'post',
        evalJSON: true,
    		parameters: list.toQueryString(),
    		onSuccess: function(result) {   
          _valuesReceived(result.responseJSON);
          Proxy.GetEventSink().fire(LICENSE.LICENSEVALUESUPDATED);  
        },			
    	  onFailure: function(value) {			  	  				
          Proxy.GetEventSink().fire(LICENSE.LICENSEVALUESUPDATED);     
      	}
    	});		  
    } catch(ex) {
      Proxy.GetEventSink().fire(LICENSE.LICENSEVALUESUPDATED);  
    }   
  }
  
  function _valuesReceived(newValues)
  {  
    if ((newValues) && (newValues.License != null)) {  
      var frame = Proxy.GetContext();
      if ((frame) && (!Object.isUndefined(frame.LicenseValues))) {        
        frame.LicenseValues = {License: newValues.License};          
      } 
    }  
  }
  
  function _updateLicense()
  {
    if (Proxy.GetValues().Application.IsClient) {
      var url = Proxy.GetValues().Application.Module +
        "?kmmagmaplatformrequesttype=newlicense" + 
        "&sid=" + Proxy.GetValues().Application.Sid +
        "&origin=settings";      
      window.location.replace(url);      
    }
  }
  
  function _updatePassword(oldPassword, newPassword, confirmPassword)
  {
    if (oldPassword == null) {
      oldPassword = "";
    }
    if (newPassword == null) {
      newPassword = "";
    }
    if (confirmPassword == null) { 
      confirmPassword = "";
    }
    
    var list = new Hash({ "sid": Proxy.GetValues().User.Sid, 
      "kmmagmaplatformrequesttype": "updatepassword", "ajax": "true",
      "password": oldPassword, "newpassword1": newPassword, 
      "newpassword2": confirmPassword});	
    	  
    try { 
    	new Ajax.Request(Proxy.GetValues().Application.Module,
    	{ method: 'post',
        evalJSON: true,
    		parameters: list.toQueryString(),
    		onSuccess: function(result) {
          try {           
            if (result.responseJSON.Parameters.result) {
              Proxy.GetEventSink().fire(LICENSE.PASSWORDUPDATED, result.responseJSON.Parameters.messagetext);
            } else {
              _lastError = result.responseJSON.Parameters.messagetext;
              Proxy.GetEventSink().fire(LICENSE.PASSWORDUPDATEERROR, result.responseJSON.Parameters.messagetext);    
            }
          } catch(ex) {
            _lastError = ex.message;
            Proxy.GetEventSink().fire(LICENSE.PASSWORDUPDATEERROR, ex.message); 
          }
        },			
    	  onFailure: function(value) {			  	  				
          _lastError = value;          
          Proxy.GetEventSink().fire(LICENSE.PASSWORDUPDATEERROR, value);    
      	}
    	});		  
    } catch(ex) {
      _lastError = ex.message;
      Proxy.GetEventSink().fire(LICENSE.PASSWORDUPDATEERROR, ex.message); 
    }        
  }
    
  function _logOff() 
  {    
    _abortLogOff = false;
    Proxy.GetEventSink().fire(LICENSE.LOGOFFBEFORE);
    if (!_abortLogOff) {
      var list = new Hash({ "sid": Proxy.GetValues().User.Sid, 
        "kmmagmaplatformrequesttype": "logout" });	
      	  
      try { 
      	new Ajax.Request(Proxy.GetValues().Application.Module,
      	{
      	  method: 'post',
          evalJSON: false,
      		parameters: list.toQueryString(),
      		onSuccess: _logOffResult,			
      	  onFailure: function(value) {			  	  				    	
            _logOffError(value);
        	}
      	});		  
      } catch(ex) {
        _logOffError(ex.message);
      }    
    }
  }
  
  function _logOffResult()
  {
    if (Proxy.GetValues().Application.Compilation !== MAGMA.COMPILATION.CLIENT) {
      Proxy.Application.PostRestart(new Hash({"ignorecookie": "true"}));    
    }
  }
  
  function _logOffError(text)
  {
    if ((text == null) || (text === "")) {
      text = "Error while logging off.";
    }
    _lastError = text;      
    Proxy.GetEventSink().fire(LICENSE.LOGOFFERROR);
  }
}