// {{{ on load:
var loading_icon;

Event.observe(window, 'load', function() {
  // Load in background:
  if(typeof(use_loading_icon) != 'undefined' && use_loading_icon[0]) {
    loading_icon = new Element('img', {alt: 'Loading Icon',
                                       src: use_loading_icon[0]});
  }

  if($('LOGON'))
    Event.observe($('LOGON'), 'submit', IsValid);


  setTimeout('checkAdminArea()', 500);

  $('username').observe('change', checkIsAdmin)
               .observe('keyup', checkIsAdmin);

  if(GetCookie('remember_login')) {
    if(GetCookie('username'))
      $('username').value = GetCookie('username');

    if($('password') && GetCookie('password'))
      $('password').value = GetCookie('password');

    if($('admin_button') && GetCookie('admin_button'))
      $('admin_button').checked = true;

    $('remember_login').checked = true;
  }

}); // }}}

// {{{ checkIsAdmin()
function checkIsAdmin() {
  checkAdminArea();

  if($F('username') !== 'admin' && $('admin_button')) {
    $$('.auth_with_admin').each(function(el) {
      el.removeClassName('auth_with_admin');
    });
  }
} // }}}

// {{{ IsValid()
function IsValid(ev){
  if(!ev)
    return false;

  if(!$F('username') || !$F('password')){

    window.alert("You must enter both your user name and your password");
    ev.stop();
    return false;
  }

  // # quick, load up the loading image:
  if(loading_icon) {
    var loader = new Loader({
      title: 'Logging In ... ',
      img: loading_icon,
      position : {
        src: $$('.authtable')[0],
        offset : {
          setWidth: false,
          setHeight: false,
          offsetLeft: 225,
          offsetTop: 60
        }
      }
    });
  }

  if($('remember_login').checked) {
    SetCookie('username', $F('username'), expdate.toGMTString());
    SetCookie('password', $F('password'), expdate.toGMTString());
    SetCookie('remember_login', 'on', expdate.toGMTString());
    SetCookie('admin_button', $F('admin_button'), expdate.toGMTString());
  } else {
    SetCookie("username", '', -1);
    SetCookie("password", '', -1);
    SetCookie("remember_login", '', -1);
    SetCookie("admin_button", '', -1);
  }

  return true;
} // }}}

// {{{ checkAdminArea()
function checkAdminArea() {
  var adminRow = $('adminrow');
  if(!adminRow)
    return;
  var adBut = $('admin_button');


  if($F('username') != 'admin') {
    if(adBut) adBut.checked = false;
    adminRow.hide();
    return;
  }

  adminRow.show();

  if(adBut && Cookie.get('admin_button')) {
    adBut.checked = true;
  }

/*
  $$('.authlabel').each(function(el) {
    var ta = el.getStyle('text-align');
    el.setStyle({textAlign: ta || 'right'});
  });
*/
} // }}}
