/**
 * @Description Ext.ux.LoginWindow for ExtJS 2.x and 3.x
 * @author  Wemerson Januario (Brazil - Goiânia)
 * @author  Albert Varaksin
 * @author  Sumit Madan
 * @license LGPLv3 http://www.opensource.org/licenses/lgpl-3.0.html
 * @version 1.0, 09/05/2009
 */
Ext.namespace('Ext.ux');
/**
 * Construtor da janela de login
 *
 * @param {Object} config
 * @extends {Ext.util.Observable}
 */
      
Ext.ux.LoginWindow = function(config) {
  Ext.apply(this, config); 
  // Css necessário para criar a extensão.
  var css = "#login-logo .x-plain-body {background:#f9f9f9 url('" + this.basePath + "/" + this.winBanner + "') no-repeat;}" + "#login-form  {background: " + this.formBgcolor + " none;}" + ".ux-auth-header-icon {background: url('" + this.basePath + "/locked.gif') 0 4px no-repeat !important;}" + ".ux-auth-form {padding:10px;}"+ ".ux-auth-login {background-image: url('" + this.basePath + "/key.gif') !important}"
            + ".ux-auth-close {background-image: url('" + this.basePath + "/close.gif') !important}";
    
  Ext.util.CSS.createStyleSheet(css, this._cssId); 
  // Eventos do LoginWindow
  this.addEvents({
    'show': true,
    'reset': true,
    'submit': true,
    'submitpass': true
  });
  Ext.ux.LoginWindow.superclass.constructor.call(this, config);
	  
  //Painel topo (Logotipo do sistema)
  this._logoPanel = new Ext.Panel({
    baseCls: 'x-plain',
    id: 'login-logo',
    region: 'center'
  }); 
  
    this.usernameId = Ext.id();
  this.passwordId = Ext.id();
  this.emailId = Ext.id();
  this.emailFieldsetId = Ext.id();
  this._requestAccountButtonId = Ext.id();
  this.languageId = Ext.id();
  this._loginButtonId = Ext.id();
  this._loginOpenIdButtonId = Ext.id();
  this._resetButtonId = Ext.id();
  this._helpButtonId = Ext.id();
  this._passwordButtonId = Ext.id();
  this._WinPasswordButtonId = Ext.id(); //Painel do formulário  

  
  this._formPasswordPanel = new Ext.form.FormPanel({
    bodyStyle: "padding: 5px;",
    id: 'password-form',
    waitMsgTarget: true,
    labelWidth: 50,
    autoHeight: true,
    buttonAlign: 'center',
    baseParams: {
      task: 'forgotPassword'
    },
    items: [{
      layout: 'form',
      border: false,
      items: [{
        xtype: 'fieldset',
        title: this.emailFieldset,
        id: this.emailFieldsetId,
        autoHeight: true,
        items: [{
          xtype: 'textfield',
          vtype: this.emailVtype,
          id: this.emailId,
          name: this.emailField,
          fieldLabel: this.emailLabel,
          vtype: this.emailVtype,
          validateOnBlur: false,
          anchor: '98%',
          allowBlank: false
        }]
      }]
    }],
    buttons: [{
      text: this.passwordButton,
      id: this._WinPasswordButtonId,
      width: 100,
      handler	: this.Passwordsubmit,
      scope: this
    }]
  }); 
  this._windowPassword = new Ext.Window({
		width: 350,
		height: 160,
		closable: true,
		resizable: false,
		draggable: this.draggable,
		modal: this.modal,
		iconCls: 'ux-auth-header-icon',
		title: this.Passwordtitle,
		bodyStyle: 'padding:5px;',
		keys: keys,
		closeAction: 'hide',
		items: [this._formPasswordPanel]
	}); 
  
  
  // Seta id para o elementos
  this._formPanel = new Ext.form.FormPanel({
    region: 'south',
    border: false,
    bodyStyle: "padding: 5px;",
    baseCls: 'x-plain',
    id: 'login-form',
    waitMsgTarget: true,    
    labelWidth: 80,
    defaults: {
      width: 300
    },
    baseParams: {
      task: 'login'
    },
    listeners: {
      'actioncomplete': {
        fn: this.onSuccess,
        scope: this
      },
      'actionfailed': {
        fn: this.onFailure,
        scope: this
      }
    },
	height: 110, //80
    items: [{
      xtype: 'label',
      id: 'titi',
	  html: '<div id="titi">&nbsp;</div>'
    },{
      xtype: 'textfield',
      id: this.usernameId,
      name: this.usernameField,
      fieldLabel: this.usernameLabel,
      vtype: this.usernameVtype,
      validateOnBlur: false,
      allowBlank: false
    },
    {
      xtype: 'textfield',
      inputType: 'password',
      id: this.passwordId,
      name: this.passwordField,
      fieldLabel: this.passwordLabel,
      vtype: this.passwordVtype,
      validateOnBlur: false,
      allowBlank: false
    },{
      xtype: 'label',
	  id: 'recoverPass',
      html: '<div style="margin-left: 90"><a href="http://intranet.fungalgenomics.ca/intwiki/EnzymeTracker_Documentation#Login.2FAccount" id="'+this._helpButtonId+'">Help</a>&nbsp; | &nbsp;<a href="mailto:ttriplet@gene.concordia.ca?subject=EnzymeTracker account request" id="'+this._requestAccountButtonId+'">Request account</a></div>'
    },{
      xtype: 'iconcombo',
      id: this.languageId,
	  hidden:true,
      hiddenName: this.languageField,
      fieldLabel: this.languageLabel,
      store: new Ext.data.SimpleStore({
        fields: ['languageCode', 'languageName', 'countryFlag'],
        //data: [['ptbr', 'Portuguese - Brazil', 'ux-flag-br'], ['eses', 'Spanish - Spain', 'ux-flag-es'], ['frfr', 'French - France', 'ux-flag-fr'], ['itit', 'Italian - Italy', 'ux-flag-it'], ['enus', 'English - The United States', 'ux-flag-us']]
        data: [['frfr', 'Francais', 'ux-flag-qc'], ['enus', 'English', 'ux-flag-ca']]
      }),
      valueField: 'languageCode',
      value: this.defaultLanguage,
      displayField: 'languageName',
      iconClsField: 'countryFlag',
      triggerAction: 'all',
      editable: false,
      mode: 'local'
    },
    {
      xtype: 'label',
      id: 'warningId',
	  html: '<div id="warningMessage"></div>'
    }]
  });
  Ext.getCmp(this.languageId).on('select',
  function() {
    this.defaultLanguage = Ext.getCmp(this.languageId).getValue(); //var lang = this.defaultLanguage; 	
    this.setlanguage();
  },
  this); 

  // Botões padrões
  var buttons = [{
		id: this._loginOpenIdButtonId,
		text: ' ',//this.loginButton,
		//hidden: true,
		handler: this.submitOpenId,
		iconCls: 'icon-loginOpenIDPanel',	                        
		scale: 'medium',
		scope: this
	},{
		id: this._loginButtonId,
		text: ' ',//this.loginButton,
		handler: this.submit,
		iconCls: 'icon-loginPanel',	                        
		scale: 'medium',
		scope: this
	}];
  var keys = [{
    key: [10, 13],
    //Tecla ENTER
    handler: this.submit,
    scope: this
  }]; 
  //Testa se o botão que recupera senha existe
  if (typeof this.passwordButton == 'string') {
    buttons.push({
      id: this._passwordButtonId,
      text: this.passwordButton,      
      handler: this.password,
      scale: 'medium',
      scope: this
    });
  } 
  //Testa se o botão que reseta o formulário existe
  if (false && typeof this.resetButton == 'string') {
    buttons.push({
      id: this._resetButtonId,
      text: ' ',//this.resetButton,      
      iconCls: 'icon-cancel',	                        
      handler: this.reset,
      scale: 'medium',
      scope: this
    });
    keys.push({
      key: [27],
      //Tecla ESC
      handler: this.reset,
      scope: this
    });
  } 
  //Cria a janela principal de login
  this._window = new Ext.Window({
    width: 429,
	height: 320, //290
    closable: false,
    resizable: false,
    modal: this.modal,
    draggable: this.draggable,
    iconCls: 'ux-auth-header-icon',
    title: this.title,
    layout: 'border',
    bodyStyle: 'padding:5px;',
    buttons: buttons,
    buttonAlign: 'center',
    keys: keys,
    plain: false,
    items: [this._logoPanel, this._formPanel]
  }); 
  //Cria a janela de recuperação de senha

  //Seta foco no campo username quando a janela principal é exibida
  // Dispara o evento "show"
  this._window.on('show',
  function() {
    this.setlanguage();
    Ext.getCmp(this.usernameId).focus(false, true);    
    this.fireEvent('show', this);
  },
  this);
}; 
// Extende a classe Ext.util.Observable
Ext.extend(Ext.ux.LoginWindow, Ext.util.Observable, {
  /**
     * Título da janela principal
     *
     * @type {String}
     */
  title: '',
  /**
     * Título da janela de recuperação de senha
     *
     * @type {String}
     */
  Passwordtitle: '',  
    /**
     * Título do fieldset da janela de recuperação de senha
     *
     * @type {String}
     */
  emailFieldset: '',  
  /**
     * Mensagem de espera ao enviar os dados
     *
     * @type {String}
     */
  waitMessage: '',
  /**
     * Texto do botão de login
     *
     * @type {String}
     */
  //loginButton : Ext.lang.us.login,
  loginButton: '',
  /**
     * Texto do botão de recuperação de senha
     *
     * @type {String}
     */
  passwordButton: '',
  /**
     * Texto do botão limpar
     *
     * @type {String}
     */
  resetButton: '',
  /**
     * Título do campo usuário
     *
     * @type {String}
     */
  usernameLabel: '',
  /**
     * Nome do campo usuário
     *
     * @type {String}
     */
  usernameField: 'username',
  /**
     * Validação do campo usuário
     *
     * @type {String}
     */
  usernameVtype: 'cubiqueUsername',
  /**
     * Título do campo email
     *
     * @type {String}
     */
  emailLabel: '',
  /**
     * Nome do campo email
     *
     * @type {String}
     */
  emailField: 'email',
  /**
     * Validação do campo email
     *
     * @type {String}
     */
  emailVtype: 'email',
  /**
     * Título do campo senha
     *
     * @type {String}
     */
  passwordLabel: '',
  /**
     * Nome do campo senha
     *
     * @type {String}
     */
  passwordField: 'password',
  /**
     * Validação do campo senha
     *
     * @type {String}
     */
  passwordVtype: 'alphanum',
  /**
     * Nome do combo idioma
     *
     * @type {String}
     */
  languageField: 'lang',
  /**
     * Título do iconcombobox idioma
     *
     * @type {String}
     */
  languageLabel: '',
  /**
     * Url de requisição de login
     *
     * @type {String}
     */
  url: '',
  /**
     * Url de requisição de recuperação de senha
     *
     * @type {String}
     */
  emailUrl: '',  
  /**
     * Url de destino caso login seja efetivado
     *
     * @type {String}
     */
  locationUrl: '',
  /**
     * Diretório das imagens
     *
     * @type {String}
     */
  basePath: 'img',
  /**
     * Logotipo do sistema (Banner)
     *
     * @type {String}
     */
  winBanner: '',
  /**
     * Cor de fundo do formulário
     *
     * @type {String}
     */
  formBgcolor: '',
  /**
     * Método de envio do formulário
     *
     * @type {String}
     */
  method: 'post',
  /**
     * Abrir janela modal
     *
     * @type {Bool}
     */
  modal: false,
  /**
     * Identificador do CSS
     *
     * @type {String}
     */
  _cssId: 'ux-LoginWindow-css',
  /**
     * Painel topo (Logotipo do sistema)
     *
     * @type {Ext.Panel}
     */
  _logoPanel: null,
  /**
     * Painel do formulário
     *
     * @type {Ext.form.FormPanel}
     */
  _formPanel: null,
  /**
     * Objeto da janela principal
     *
     * @type {Ext.Window}
     */
  _window: null,
  /**
     * Objeto da janela de recuperação de senha
     *
     * @type {Ext.Window}
     */
  _windowPassword: null,
  /**
     * Exibe a  janela principal
     *
     * @param {Ext.Element} el
     */
  show: function(el) {
    this._window.show(el);
  },
  /**
     * Exibe a  janela de recuperação de senha
     *
     * @param {Ext.Element} el
     */
  password: function(el) {
    this._windowPassword.show(el);
  },
  /**
     * Limpa o formulário
     */
  reset: function() {
    if (this.fireEvent('reset', this)) {
      this._formPanel.getForm().reset();
    }
  },  
  /**
     * Idioma padrão do formulário
     */
  defaultLanguage: 'ptbr',
  /**
     * Seleciona o idioma
     */
  setlanguage: function() {
    Ext.override(Ext.form.Field, {
      setFieldLabel: function(text) {
        if (this.rendered) {
          this.el.up('.x-form-item', 10, true).child('.x-form-item-label').update(text);
        } else {
          this.fieldLabel = text;
        }
      }
    });
    if (this.defaultLanguage == 'ptbr') {
      this._window.setTitle('Autenticação');
      this._windowPassword.setTitle('Recuperar senha');
      Ext.getCmp(this._loginButtonId).setText('Entrar');
      Ext.getCmp(this._passwordButtonId).setText('Recuperar senha');
      Ext.getCmp(this._resetButtonId).setText('Limpar');
      Ext.getCmp(this._WinPasswordButtonId).setText('Recuperar senha');
      Ext.getCmp(this.emailId).setFieldLabel('Email');
      Ext.getCmp(this.emailFieldsetId).setTitle('Digite seu email'); 
      Ext.getCmp(this.usernameId).setFieldLabel('Usuário:');
      Ext.getCmp(this.passwordId).setFieldLabel('Senha:');
      Ext.getCmp(this.languageId).setFieldLabel('Idioma:');      
      this.waitMessage = 'Enviando dados...';  
    } else if (this.defaultLanguage == 'eses') {
      this._window.setTitle('Autenticación');
      this._windowPassword.setTitle('Recuperar contraseña');
      Ext.getCmp(this._loginButtonId).setText('Inicio');
      Ext.getCmp(this._passwordButtonId).setText('Recuperar contraseña');
      Ext.getCmp(this._resetButtonId).setText('Limpiar');
      Ext.getCmp(this._WinPasswordButtonId).setText('Recuperar contraseña');
      Ext.getCmp(this.emailId).setFieldLabel('Email');
      Ext.getCmp(this.emailFieldsetId).setTitle('Ingrese su e-mail');
      Ext.getCmp(this.usernameId).setFieldLabel('Usuario:');
      Ext.getCmp(this.passwordId).setFieldLabel('Contraseña:');
      Ext.getCmp(this.languageId).setFieldLabel('Idioma:');
      this.waitMessage = 'Envío de datos...'; 
      } else if (this.defaultLanguage == 'frfr') {
      this._window.setTitle('Authentification');
      this._windowPassword.setTitle('Récupérer le mot de passe');
      Ext.getCmp(this._loginButtonId).setText('Entrer');
      Ext.getCmp(this._loginOpenIdButtonId).setText('<b>Entrer avec Cubique</b>');
      Ext.getCmp(this._passwordButtonId).setText('R&eacute;cup&eacute;rer le mot de passe');
      Ext.get(this._requestAccountButtonId).innerHTML = 'Demander un compte';
      //Ext.getCmp(this._resetButtonId).setText('Effacer');
      Ext.getCmp(this._WinPasswordButtonId).setText('R&eacute;cup&eacute;rer le mot de passe');
      Ext.getCmp(this.emailId).setFieldLabel('E-mail');
      Ext.getCmp(this.emailFieldsetId).setTitle('Entrez votre email');
      Ext.getCmp(this.usernameId).setFieldLabel('Utilisateur:');
      Ext.getCmp(this.passwordId).setFieldLabel('Mot de passe:');
      //Ext.getCmp(this.languageId).setFieldLabel('Langue:');
      this.waitMessage = 'Envoi de donn&eacute;es...'; 
    } else if (this.defaultLanguage == 'itit') {	
    	this._window.setTitle('Autenticazione');
      this._windowPassword.setTitle('Recuperare la password');
      Ext.getCmp(this._loginButtonId).setText('Inserisci');
      Ext.getCmp(this._passwordButtonId).setText('Recuperare la password');
      Ext.getCmp(this._resetButtonId).setText('Cancella');
      Ext.getCmp(this._WinPasswordButtonId).setText('Recuperare la password');
      Ext.getCmp(this.emailId).setFieldLabel('E-mail');
      Ext.getCmp(this.emailFieldsetId).setTitle('Inserisci la tua e-mail');
      Ext.getCmp(this.usernameId).setFieldLabel('Utente:');
      Ext.getCmp(this.passwordId).setFieldLabel('Password:');
      Ext.getCmp(this.languageId).setFieldLabel('Lingua:');   
      this.waitMessage = 'Invio di dati...';  	
    } else if (this.defaultLanguage == 'enus') {	
      this._window.setTitle('Authentication');
      this._windowPassword.setTitle('Recover password');
      Ext.getCmp(this._loginButtonId).setText('Login');
      Ext.getCmp(this._loginOpenIdButtonId).setText('<b>Login with Cubique&nbsp;</b>');
      Ext.getCmp(this._passwordButtonId).setText('Recover password');
      Ext.get(this._requestAccountButtonId).innerHTML = 'Request account';
      //Ext.getCmp(this._resetButtonId).setText('Reset');
      Ext.getCmp(this._WinPasswordButtonId).setText('Recover password');
      Ext.getCmp(this.emailId).setFieldLabel('Email');
      Ext.getCmp(this.emailFieldsetId).setTitle('Enter your email');
      Ext.getCmp(this.usernameId).setFieldLabel('Username:');
      Ext.getCmp(this.passwordId).setFieldLabel('Password:');
      //Ext.getCmp(this.languageId).setFieldLabel('Language:');
      this.waitMessage = 'Sending data...';     	
    } 
  },
  
  /**
     * Envia a requisição de login
     */
    submit : function () {
        var form = this._formPanel.getForm();

        if (form.isValid()) {
            Ext.getCmp(this._loginButtonId).disable();
            if(Ext.getCmp(this._cancelButtonId)) {
                Ext.getCmp(this._cancelButtonId).disable();
            }
			Ext.getCmp(this.passwordId).setValue(hex_md5(Ext.getCmp(this.passwordId).getValue()));
            if (this.fireEvent('submit', this, form.getValues()))  {
                form.submit ({
                    url     : this.url,
                    method  : this.method,
                    waitMsg : this.waitMessage,
                    success : this.onSuccess,
                    failure : this.onFailure,
                    scope   : this
                });
            }
		}
    },
	
	submitOpenId : function() {
		window.location = "php/login_openid.php";
	},
    
    /**
     * Envia a requisição de recuperação de senha 
     */
    Passwordsubmit : function () {
        var form = this._formPasswordPanel.getForm();

        if (form.isValid())
        {
            Ext.getCmp(this._WinPasswordButtonId).disable();
            if (this.fireEvent('submitpass', this, form.getValues()))
            {
                form.submit ({
                    url     : this.emailUrl,
                    method  : this.method,
                    waitMsg : this.waitMessage,
                    success : this.onEmailSuccess,
                    failure : this.onEmailFailure,
                    scope   : this
                });
            }
        }
    },
    
  /**
     * Se receber sucesso
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
  onSuccess: function(form, action) {
    if (action && action.result) {
      window.location = this.locationUrl;
    }
  },
  /**
     * Se receber falha
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
  onFailure: function(form, action) { // enable buttons
    Ext.getCmp(this.passwordId).setValue('');
	Ext.getCmp(this._loginButtonId).enable();
    if (Ext.getCmp(this._resetButtonId)) {
      Ext.getCmp(this._resetButtonId).enable();
    }
	document.getElementById('warningMessage').innerHTML = '<span class="tooltip-warning">'+action.result.msg+'</span>';
	Ext.getCmp(this.passwordId).focus();
  },  
  /**
     * Se receber sucesso
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
  onEmailSuccess: function(form, action) {
    if (action && action.result) {
    	this._windowPassword.hide();
    	Ext.MessageBox.show({
								title: action.result.title,
								msg: action.result.msg,
								buttons: Ext.MessageBox.OK,
								icon: Ext.MessageBox.INFO
							});
    }
  },
  /**
     * Se receber falha
     *
     * @param {Ext.form.BasicForm} form
     * @param {Ext.form.Action} action
     */
  onEmailFailure: function(form, action) { 
  	// Ativa os botões
    Ext.getCmp(this._WinPasswordButtonId).enable();
    Ext.MessageBox.show({
							title: action.result.title,
							msg: action.result.msg,
							buttons: Ext.MessageBox.OK,
							icon: Ext.MessageBox.WARNING
						});
  }
});

var cubiqueUsernameTest = /^([\w-.]+)$/i;
Ext.apply(Ext.form.VTypes, {
    //  vtype validation function
    cubiqueUsername: function(val, field) {
        return cubiqueUsernameTest.test(val);
    },
    // vtype Text property: The error text to display when the validation function returns false
    cubiqueUsernameText: 'Not a valid username.  Must contains letters, dashes and dots only.',
    // vtype Mask property: The keystroke filter mask
    cubiqueUsernameMask: /[\w.-]/i
});

