// login box management functions
  
function initLoginBox()
{
  // dependency is loaded
  dependencyLoaded('login');
}
  
// sends the request to login
function sendLogin()
{
  var login = obtainElementById( 'login' ).value;
  var password = obtainElementById( 'password' ).value;
  
  // checking to have something to do
  if ( login == "" || login == defaultLoginValue )
  {
    if ( LANGUAGE == 'ru' )
    {
      alert( "Вы забыли ввести имя пользователя" );
    }
    else
    {
      alert( "You've forgotten to enter a user name" );
    }
    return;
  };
  if ( password == "" || password == defaultPasswordValue )
  {
    if ( LANGUAGE == 'ru' )
    {
      alert( "Вы забыли ввести пароль" );
    }
    else
    {
      alert( "You've forgotten to enter a password" );
    }
    return;
  };
        
  // building the list of params
  var params = new Array();
  params[PARAM_USER_ID] = login;
  params[PARAM_PASSWORD] = password;
  
  // adding the resource to the document
  sendUrlResponseTextToFunction
  ( 
    sendLoginRequestUrl, 
    function( response )
    {
      if ( response == RESPONSE_REQUEST_PROCEEDED_SUCCESSFULLY )
      {
        // removing the password by the sequrity reasons
        obtainElementById( 'login' ).value = "";
        obtainElementById( 'password' ).value = "";
        // saving the new login value
        updatePageForLogin( login )
      }
      else if ( response == RESPONSE_INCORRECT_LOGIN )
      {
        if ( LANGUAGE == 'ru' )
        {
          alert( 'Неверный логин или пароль' );
        }
        else
        {
          alert( 'Incorrect login or password' );
        }
      }
      else if ( response == RESPONSE_ADMONITION )
      {
        if ( LANGUAGE == 'ru' )
        {
          alert( 'Обнаружена попытка подбора пароля, при продолжении таких попыток вам будет временно заблокирован доступ к сайту' );
        }
        else
        {
          alert( 'The password hack is detected, the access to you will be blocked for some time if you will continue these actions' );
        }
      }
      else
        alert( response );
    },
    params
  );
}

// sends the request to log out
function sendLogout()
{
  sendUrlResponseTextToFunction
  ( 
    sendLogoutRequestUrl, 
    function( response )
    {
      if ( response == RESPONSE_REQUEST_PROCEEDED_SUCCESSFULLY )
      {
        // saving the new login value
        updatePageForLogin( DEFAULT_USER_ID )
      }
      else
        alert( response );
    }
  );
}

// sends the request to get the user screen name and to show it
function updateUserScreenName( userId )
{
  sendUrlResponseTextToFunction
  ( 
    getUserScreenNameRequestUrl + escape( userId ), 
    function( response )
    {
      if ( response != "" )
      {
        USER_SCREEN_NAME = response;
        // displaying the user name
        var el = obtainElementById( 'userScreenName' );
        if ( el )
        {
          el.innerHTML = "<a href='"+userProfileUrlCommonPart+USER_ID+"'>"+(LANGUAGE=='ru'?"Личный кабинет":"Member Area")+" "+USER_SCREEN_NAME+"</a>";
        }
      };
    }
  );
}

// sends the request to get the user rights and to update some 
// of the page's controls
function updateUserRights()
{
  sendUrlResponseXmlToFunction
  ( 
    getUserRightsRequestUrl + USER_ID, 
    function( response )
    {
      if ( typeof( response ) == "object" )
      {
        var temp = 0;
        
        temp = response.getElementsByTagName("USER_RIGHTS_READ");
        if ( temp.length > 0 && temp[0].firstChild && temp[0].firstChild.nodeValue == "1" )
          USER_RIGHTS_READ = true;
        else
          USER_RIGHTS_READ = false;
          
        temp = response.getElementsByTagName("USER_RIGHTS_EDIT");
        if ( temp.length > 0 && temp[0].firstChild && temp[0].firstChild.nodeValue == "1" )
          USER_RIGHTS_EDIT = true;
        else
          USER_RIGHTS_EDIT = false;
          
        temp = response.getElementsByTagName("USER_RIGHTS_ADD");
        if ( temp.length > 0 && temp[0].firstChild && temp[0].firstChild.nodeValue == "1" )
          USER_RIGHTS_ADD = true;
        else
          USER_RIGHTS_ADD = false;
          
        temp = response.getElementsByTagName("USER_RIGHTS_DELETE");
        if ( temp.length > 0 && temp[0].firstChild && temp[0].firstChild.nodeValue == "1" )
          USER_RIGHTS_DELETE = true;
        else
          USER_RIGHTS_DELETE = false;
          
        temp = response.getElementsByTagName("USER_RIGHTS_COMMENT");
        if ( temp.length > 0 && temp[0].firstChild && temp[0].firstChild.nodeValue == "1" )
          USER_RIGHTS_COMMENT = true;
        else
          USER_RIGHTS_COMMENT = false;
          
        temp = response.getElementsByTagName("USER_RIGHTS_SETUP");
        if ( temp.length > 0 && temp[0].firstChild && temp[0].firstChild.nodeValue == "1" )
          USER_RIGHTS_SETUP = true;
        else
          USER_RIGHTS_SETUP = false;
          
        temp = response.getElementsByTagName("USER_RIGHTS_MODERATE");
        if ( temp.length > 0 && temp[0].firstChild && temp[0].firstChild.nodeValue == "1" )
          USER_RIGHTS_MODERATE = true;
        else
          USER_RIGHTS_MODERATE = false;
        
        // dependency is loaded
        dependencyLoaded('authorization');
        
        // updating the dependent controls
        // the following funtions may just not to be in some modes
        try
        {
          addDependentCallback(function(){
            updateManagementBoxButtons( managementBoxId );
          },'management, login');
        } catch (e) {window.status='loginBox::updateUserRights()::updateManagementBoxButtons '+e.message};
        try
        {
          updateRegisterBox( "registerbox" );
        } catch (e) {window.status='loginBox::updateUserRights()::updateRegisterBox '+e.message};
        try
        {
          addDependentCallback(function(){
          //  updateUserInfo();
          },'login');
        } catch (e) {window.status='loginBox::updateUserRights()::updateUserInfo '+e.message};
        try
        {
          addDependentCallback(function(){
            updateCallback(true);
          },'module,userId,editor');
        } catch (e) {window.status='loginBox::updateUserRights()::updateCallback '+e.message};
        try
        {
          updateCart();
        } catch (e) {window.status='loginBox::updateUserRights()::updateCart '+e.message};
      };
    }
  );
}

// updates all the page settings, which depend on user's ID:
// login forms, management buttons, etc.
// if updateAnyWay is set to true, this routine will be forced to run
function updatePageForLogin( userId, updateAnyWay )
{
  if ( userId != USER_ID || updateAnyWay )
  {
    USER_ID = userId;
        
    // updating the user screen name and depending page controls
    updateUserScreenName( userId, LANGUAGE );
    // updating the access rights and depending page controls
    updateUserRights();
    // dependency is loaded
    dependencyLoaded('userId');
    // updating the site structure
    try
    {
      addDependentCallback(function(){refreshSiteStructureData()},'settings,module');
    } catch (e) {window.status='loginBox::updatePageForLogin()::refreshSiteStructureData '+e.message};
    // updating the profile management button
    try
    {
      updateProfileButton();
    } catch (e) {/** /window.status='loginBox::updatePageForLogin()::updateProfileButton '+e.message/**/};
    // updating the accessors list
    try
    {
      addDependentCallback(function(){
        updateAccessorsList();
      },'accessors');
    } catch (e) {window.status='loginBox::updatePageForLogin()::updateAccessorsList '+e.message};
    
    // updating the login form view
    if ( userId == DEFAULT_USER_ID )
    {
      // updating the login form
      obtainElementById( 'loginform' ).style.display = loginBoxDisplayType;
      obtainElementById( 'logoutform' ).style.display = "none";
    }
    else
    {
      // updating the login form
      obtainElementById( 'loginform' ).style.display = "none";
      obtainElementById( 'logoutform' ).style.display = loginBoxDisplayType;
    };
    try
    {
      //clearDocumentData();
      //updateCallback(true);
      //prepareCommentBoxForDefaultFunctionality();
    } catch (e) {window.status='loginBox::updatePageForLogin()::updateCallback '+e.message};
    try
    {
      addDependentCallback(function(){displayAdvertisements()},'settings,module,advertisements');
    } catch (e) {/** /window.status='loginBox::updatePageForLogin()::displayAdvertisements '+e.message/**/};
    try
    {
      addDependentCallback(function(){displayNews()},'settings,module,news');
    } catch (e) {/** /window.status='loginBox::updatePageForLogin()::displayNews '+e.message/**/};
  };
}

// obtains the current user's ID and performs the reconfiguration
// if the user ID, obtained, differs from the stored one
function updateCurrentUserId()
{
  // adding the resource to the document
  sendUrlResponseTextToFunction
  ( 
    getUserIdRequestUrl, 
    function( response )
    {
      // displaying the message for the user to know, that he's
      // not authorized any more
      if ( USER_ID != DEFAULT_USER_ID && 
           USER_ID != "" && 
           response != DEFAULT_USER_ID && 
           response != USER_ID )
        alert( "Вы не авторизованы." );

      // updating the configuration
      if ( response != USER_ID )
      {
        updatePageForLogin( response );
      };
    }
  );
}

// starts running and updating this box
function startLoginBoxUpdate()
{
  addDependentCallback(function()
  {
    // default initialization
    updateCurrentUserId();
    // this operation should be performed periodically
    setInterval( function()
      {
        updateCurrentUserId()
      },
      LOGIN_STATE_UPDATE_PERIOD 
    )
  },'ajax,settings,constants,login');
}
  
// INIT
addDependentCallback(function(){
  initLoginBox();
},'ajax,helperFunctions,loginSettings');

