var curUserID ="";
var userType = -1;

function $(id) { // short hand for getElementById
  return document.getElementById(id);
}

function init() {
  $('register').style.display='none'; // hide the register div
  $('registerlink').style.display='block'; // show the toggle link
}

function toggleRegisterForm() { // toggles register form
  if($('register').style.display=='block') {
    $('register').style.display='none';
    $('login').style.display='block';
    $('registerlink').innerHTML='register';
  } else {
    $('register').style.display='block';
    $('login').style.display='none';
    $('registerlink').innerHTML='login';
  }
}

function checkThis()
{
/*
  var els = document.getElementsByName("login_password");
  alert(els.length);
  var el = document.getElementById("login_password");
  alert("pw:"+el.value);
  */
}

function hashPass() { // hash the password field from login form
  //alert($('login_password').value);
  $('login_pass_md5').value=MD5($('login_password').value); // set the value of the hidden field
  $('login_password').value=''; // clear the password field
  if ($("remembermech").getAttribute("checked") == 'checked')
  {
    SetCookie("aovusername", $("login_name").value, 3000);
    SetCookie("aovdisplayname", $('login_pass_md5').value, 3000);
  }
}

function hashPass2() { // hash the password field from login form
  //alert($('login_password').value);
  $('login_pass_md5').value=MD5($('login_password').value); // set the value of the hidden field
  $('login_password').value=''; // clear the password field
  
}

function removeUser()
{
  this.DeleteCookie("aovusername");
  this.DeleteCookie("aovdisplayname");
}

function hashPasses() { // hash the password fields from register form
  $('register_pass_1_md5').value=MD5($('register_password_1').value);
  $('register_pass_2_md5').value=MD5($('register_password_2').value);
  $('register_password_1').value='';
  $('register_password_2').value='';
}

// declare AJAX request variable
var http_request;

function newHTTPRequest() { // create a new http request
  if (window.XMLHttpRequest) { // create http request for any decent browser...
    return new XMLHttpRequest();
  } else if (window.ActiveXObject) { // ... for Internet Explorer
    try {
      return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        return new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }
  // Something went wrong
  if (!http_request) {
    return false;
  }
}

function showErrorMessage(top,text) {
  var lval = $("login_name");
  if (lval.value !="" && lval.getAttribute("emptytext") != lval.value)
  {
    this.showBox($("login_password"),"Kombinationen af brugernavn og kode er forkert");
  }

/*
    $('error').style.marginTop=top+'px';	// set the top value
	$('error_content').innerHTML=text;		// set the error text
	$('error').style.display="block";		// and show the error popup
	// start the timer to hide the error popup after two seconds
	helptimer=window.setTimeout("document.getElementById('error').style.display = 'none';",2000);
  */
}

/**** LOGIN *******************************************/
function checkLogin() { // CHECK THE LOGIN
  // check if login username is empty
  if($('login_name').value=="") { // no login name
    showErrorMessage(16,'Please enter a username!'); // and pop the error message
  } else {
    // No error so far? Then let's send the database query via AJAX
    http_request=newHTTPRequest(); // create new AJAX request
    if(!http_request) { // creating new request failed, return true so that form is posted
      return true;
    }
    // This funtion will be called each time the state of the request changes. (like a Windows event handler)
    http_request.onreadystatechange=refreshLoginForm;
    // Open the request
    http_request.open('POST','admin/functions.php',true);
    // tell the server that we are POSTing information
    http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    // Send the request with the POST variables
    curUserID = $('login_name').value;
    http_request.send('action=login&login_name='+$('login_name').value+'&login_pass_md5='+$('login_pass_md5').value+'&date='+new Date());
  }
  return false; // return false to prevent the form from submitting!
}

function refreshLoginForm() { // this is the event handler function for login form AJAX requests
  // check the state of the request ( 0 = not initialised; 1 = loading; 2 = loaded; 3 = interacting; 4 = complete).
  if (http_request.readyState == 4) { // request complete!
    //	$('submit_button').value = "Login"; // Set the button text.
    // check the response status - should be 200 (not 404 or 301....)
    var result=http_request.responseText;
    //alert(result);
    if (http_request.status==200) {
      result=http_request.responseText; // get the response
      //alert(result);
      switch(result) {
        case '0':
          // all correct, show message
          updatePage(true,curUserID);
          //$('wrapper').innerHTML='<div><p>Hello '+$('login_name').value+'! You are logged in.</p><p><a href="another_page.php">Another page.</a></p><p><a href="?logout=true">Log me out!</a></p></div>';
          break;
        case '3':
          // password incorrect
          // updatePage();
          showErrorMessage(41,'Password is incorrect!');
          break;
        default:
          // user not found
          //updatePage();
          showErrorMessage(16,'Username does not exist!');
          break;
      }
    } else { // server error (404, 301)
      alert('Server Error!');
    }
  } else { // not yet ready, show loading
//$('submit_button').value = "Checking..."; // Set the button text.
}
}
/***************************************************/

/****** REGISTRATION *****************************/
function checkRegistration() {
  // first, some basic checks like empty fields
  if($('register_name').value=="") { // check username
    showErrorMessage(16,'Please enter a username!');
  } else if($('register_pass_1_md5').value!=$('register_pass_2_md5').value) { // check password match
    showErrorMessage(66,'Passwords do not match!');
  } else if(!$('register_email').value.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) { // check email
    showErrorMessage(91,'Please enter a valid email!');
  } else { // do AJAX
    // No error so far? Then let's send the database query via AJAX
    http_request=newHTTPRequest(); // create new AJAX request
    if(!http_request) { // creating new request failed, return true so that form is posted
      return true;
    }
    // This funtion will be called each time the state of the request changes. (like a Windows event handler)
    http_request.onreadystatechange=refreshRegistrationForm;
    // Open the request
    http_request.open('POST','functions.php',true);
    // tell the server that we are POSTing information
    http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    // Send the request with the POST variables
    http_request.send('action=register&register_name='+$('register_name').value+'&register_pass_1_md5='+$('register_pass_1_md5').value+'&register_pass_2_md5='+$('register_pass_2_md5').value+'&register_email='+$('register_email').value);
  }
  return false; // return false stops the form action!
}

function refreshRegistrationForm() {
  // check the state of the request ( 0 = not initialised; 1 = loading; 2 = loaded; 3 = interacting; 4 = complete).
  if (http_request.readyState==4) { // request complete!
    $('submit_button2').value="Login"; // Set the button text.
    // check the response status - should be 200 (not 404 or 301....)
    if (http_request.status==200) {
      var result=http_request.responseText; // get the response
      result=result.substring(0,1); // get the first error
      switch(result) {
        case '0':
          // all correct, show message
          $('wrapper').innerHTML='<div><p>Hello '+$('login_name').value+'! You are logged in.</p><p><a href="another_page.php">Another page.</a></p><p><a href="?logout=true">Log me out!</a></p></div>';
          break;
        case '3':
          // strange error.... usually shouldn't occur....
          $('wrapper').innerHTML='<div><p class="error">'+$('login_name').value+' was registered but could not be logged in! Please try logging in again or contact the site administrator.</p></div>';
          break;
        case '4':
          // user already exists
          showErrorMessage(16,'This username already exists!');
          break;
        case '5':
          // passwords didn't match
          showErrorMessage(66,'Passwords do not match!');
          break;
        case '6':
          // invalid email format
          showErrorMessage(91,'Please enter a valid email!');
          break;
        case '7':
          // database error
          alert('DATABASE ERROR!\nPlease try again or contact the site admin.');
          break;
        default:
          // catch all other errors
          alert('UNKNOWN ERROR!\nPlease try again or contact the site admin.');
          break;
      }
    } else { // server error (404, 301)
      alert('Server Error!');
    }
  } else { // not ready yet.....
    $('submit_button2').value = "Checking..."; // Set the button text.
  }
}

function checkStartup()
{
  var us = ReadCookie("username");
  var dn = ReadCookie("displayname");
  if (us != '' && dn != '')
  {
    $('login_pass_md5').value=dn; // set the value of the hidden field
    $('login_password').value=''; // clear the password field
    $("login_name").value=us;

    var el = $("remebermech");

    //checkboxClick(el);
    //rememberMeClicked(el,'rememberme');

    checkLogin();
  }
}
//checkStartup();
/***************************************************/
