// Copyright (C) 2010 by Bricsnet FM Americas
// All rights reserved.
//
// This software is the confidential and proprietary information
// of Bricsnet. ("Confidential Information").  You shall not
// disclose such Confidential Information and shall use it only
// in accordance with the terms of the license agreement you
// entered into with Bricsnet.

if(typeof PCGUI=='undefined') throw ("Login requires PCGUI.");

var t = PCGUI.t;
var url = PCGUI.url;
var otherData = PCGUI.otherData;
var navigateTo = PCGUI.navigateTo;

handlePasswordKeyEvent= function(event) {
  var keynum;

  if (window.event) {
    keynum = event.keyCode;
  } else if (event.which) {
    keynum = event.which
  }

  if (keynum == 13) {
    Login.login(Ext.getCmp('login_window'));
  }
};

var Login = {
  creditsWindow: null,

  showCredits: function () {
    if(Login.creditsWindow == null) {
      Login.creditsWindow = new Ext.Window({
       id: 'credits_window',
       modal: true,
       width: 400,
       bodyStyle: 'background-color: #FFFFFF',
       height: 150,
       closeAction: 'hide',
       contentEl: 'credits'
      });
    }

    Login.creditsWindow.show();
  },

  login: function (loginWindow) {
    loginWindow.hide();
    PCGUI.showLoadMask(t('message.please_wait'));
    document.login_form.submit();
  },

  changeLocale: function () {
    var localeSelect = document.getElementById("locale_select");
    var selectedIndex = localeSelect.selectedIndex;
    var selectedOptionValue = localeSelect.options[selectedIndex].value;
    var changeLocaleURL = url('change_locale');
    var urlWithParams = changeLocaleURL + "?locale_name=" + selectedOptionValue;

    navigateTo(urlWithParams);
  },

  load: function() {
    Ext.onReady(function() {
      var loginWindow = new Ext.Window({
        id: 'login_window',
        title: otherData("appVersion"),
        closable: false,
        layout: 'fit',
        resizable: false,
        draggable: false,
        plain: true,
        animateTarget: false,
        bodyStyle: 'padding: 5px;',
        width: parseInt(otherData('window_width')),
        height: parseInt(otherData('window_height')),
        defaults: {
          border: false
        },

        items: [{contentEl: 'panel_login'}],

        tools: [{id: 'help', handler: Login.showCredits}],

        buttons: [
          {
            text: t('label.login'),
            handler: function () {
              Login.login(loginWindow);
            }
          }
        ]
      });

      loginWindow.show();
      loginWindow.doLayout();
    });
  }
};

Login.load();
