//var g_milliseconds_expire = 1000 * 60 * 60 * 24 * 30; // 30日：だいたい 1ヶ月
//var g_milliseconds_expire = 1000 * 60 * 60 * 24 * 7; // 1週間
var g_milliseconds_expire = 1000 * 60 * 60; // 1時間
//var g_milliseconds_expire = 1000 * 60 * 10; // 10分
//var g_milliseconds_expire = 1000 * 60; // 1分
//var g_milliseconds_expire = 1000 * 10; // 10秒

var g_uid_guest = '-'
var g_uname_guest = 'Guest';

var g_result_true  = 'b326b5062b2f0e69046810717534cb09';
var g_result_false = '68934a3e9455fa72420237eb05902327';


////////////////////////////////////////////////////////////////////////////////
//
// ログインを実行し，コールバック関数 func_callback を呼び出す
//
////////////////////////////////////////////////////////////////////////////////
function login(func_callback) {
  var user_ = document.getElementById('user_');
  var user  = document.getElementById('user'); user.innerHTML = ''; user.style.display = 'none';
  var cookie = document.cookie;

  var foot_user_ = document.createElement('div'); foot_user_.id = 'foot_user_';
  var p = document.createElement('p'); p.style.margin = '0';
  user_.appendChild(p);
  var img_open = document.createElement('img');
  img_open.id = 'user_profile_open';
  img_open.src = dir('img', 0) + 'common/icons/user_open.png';
  addListener(img_open, 'click', displayUserProfile, false);
  foot_user_.appendChild(img_open);
  user_.appendChild(foot_user_);

  user.uid = g_uid_guest;
  user.uname = g_uname_guest;
  document.getElementById('user_profile_open').title = 'ログインフォームを開きます．';
  getNode(user_, 'p', 0).innerHTML = 'ログイン状態を確認しています．．．';
  //
  // Cookie が存在しない場合，ログインを促す
  //
  if( !cookie ) {
    getNode(user_, 'p', 0).innerHTML = 'ようこそ<b> ' + getUName() + ' </b>さん';
    //
    // callback function
    //
    func_callback();
  }
  //
  // 該当する Cookie が存在する場合，ユーザディレクトリのログインファイルを照合する
  //
  else {
    ////cookie.match(/uid=(\d{10})&time=(.{32})/);
    cookie.match(/uid=(\w{32})&time=(\w{32})/);
    var uid = RegExp.$1.toString();
    var time = RegExp.$2.toString();
    var func = function(xml) {
      if( getNodeValue(xml, 'result', 0) == g_result_true ) {
        //
        // 自動ログイン成功時，Cookie の有効期限を更新
        //
        user.uid = uid;
        var time_ = setCookie_login(true);
        var func_ = function(xml_) {
          document.getElementById('user_profile_open').title = 'ユーザプロフィールを開きます．';
          user.uname = getNodeValue(xml_, 'name', 0);

        getNode(user_, 'p', 0).innerHTML = 'ようこそ<b> ' + getUName() + ' </b>さん';


          //userProfile(uid);
          //
          // callback function
          //
          func_callback();
          return;
        }
        var query = new Array();
        query.push('cmd=login');
        query.push('uid=' + user.uid);
        query.push('time=' + time_);
        httpXMLRequest(dir('cgi', 0) + 'user.cgi', 'POST', array2queryString(query), func_, httpError, 'cgi_user_login_auto_success.' + uid, true);
      }
      else {
        getNode(user_, 'p', 0).innerHTML = 'ようこそ<b> ' + getUName() + ' </b>さん';
        //
        // callback function
        //
        func_callback();
      }
    }
    var query = new Array();
    query.push('cmd=login_auto');
    query.push('uid=' + uid);
    query.push('time=' + time);
    httpXMLRequest(dir('cgi', 0) + 'user.cgi', 'POST', array2queryString(query), func, httpError, 'cgi_user_login_auto.' + user.uid, true);
  }
  return;
}



////////////////////////////////////////////////////////////////////////////////
//
// ログインフォームを生成
//
////////////////////////////////////////////////////////////////////////////////
function loginForm() {
  var user_ = document.getElementById('user_');
  var user  = document.getElementById('user'); user.innerHTML = '';
  user.style.textAlign = 'right';
  
  var h3 = document.createElement('h3');
  h3.style.textAlign = 'left';
  h3.innerHTML = 'ログイン';
  user.appendChild(h3);

  var p_msg = document.createElement('p');
  p_msg.innerHTML = 'User ID と Password を入力後，Enter キーを押してください．';
  user.appendChild(p_msg);

  //
  // User ID
  //
  var input_uid = document.createElement('input');
  input_uid.id = 'login_uid';
  input_uid.type = 'text';
  var focusToPasswd = function(e) {
    if( e.keyCode == 13 ) { document.getElementById('login_passwd').focus(); }
  }
  addListener(input_uid, 'keydown', focusToPasswd, false);
  user.appendChild(document.createTextNode('User ID: '));
  user.appendChild(input_uid);
  //
  // Passwd
  //
  var input_passwd = document.createElement('input');
  input_passwd.id = 'login_passwd';
  input_passwd.type = 'password';
  addListener(input_passwd, 'keydown', authenticate, false);
  user.appendChild(document.createElement('br'));
  user.appendChild(document.createTextNode('Password: '));
  user.appendChild(input_passwd);

  //
  // 新規登録
  //
  var p_create = document.createElement('p');
  p_create.style.margin = '6px 0 0 0';
  p_create.innerHTML = '新規登録';
  addListener(p_create, 'click', registrationForm, false);
  user.appendChild(p_create);


  //
  // フッタ
  //
  var foot_user = document.createElement('div'); foot_user.id = 'foot_user';
  var img_close = document.createElement('img');
  img_close.id = 'user_profile_close';
  img_close.src = dir('img', 0) + 'common/icons/user_close.png';
  img_close.title = 'フォームを閉じます．';
  addListener(img_close, 'click', hideUserProfile, false);
  foot_user.appendChild(img_close);
  user.appendChild(foot_user);

  input_uid.focus();
  return;
}

//
// ユーザ認証
//
function authenticate(e) {
  var user_ = document.getElementById('user_');
  var user  = document.getElementById('user');
  var target = getTargetElement(e);
  if( target.id == 'login_passwd'  &&  e.keyCode != 13 ) { return; } // Enter キーが押されたときのみ以下を実行
  var p_msg = getNode(user, 'p', 0);
  p_msg.innerHTML = '確認中です．．．';

  ////var uid_input = document.getElementById('login_uid').value;
  var uid_input = hex_md5(document.getElementById('login_uid').value);
  var passwd_input = hex_md5( document.getElementById('login_passwd').value );
 
  var func = function(xml) {
    var result = getNodeValue(xml, 'result', 0);
    //
    // 認証成功時の処理
    //
    if( result == g_result_true ) {
      p_msg.innerHTML = '認証成功．';
      user.uid = hex_md5(document.getElementById('login_uid').value);
      var time = setCookie_login(true);
      var success_auth = function(xml) {
        location.reload();
        return;
      }
      var query = new Array();
      query.push('cmd=login');
      query.push('uid=' + user.uid);
      query.push('time=' + time);
      httpXMLRequest(dir('cgi', 0) + 'user.cgi', 'POST', array2queryString(query), success_auth, httpError, 'cgi_user_authenticate_success.' + user.uid, true);
    }
    //
    // 認証失敗時の処理
    //
    else {
      p_msg.innerHTML = 'ID または Password に誤りがあります．';
      document.getElementById('login_uid').value = '';
      document.getElementById('login_passwd').value = '';
      document.getElementById('login_uid').focus();
    }
    return;
  }
  var query = new Array();
  query.push('cmd=authenticate');
  query.push('uid=' + uid_input);
  query.push('passwd=' + passwd_input);
  httpXMLRequest(dir('cgi', 0) + 'user.cgi', 'POST', array2queryString(query), func, httpError, 'cgi_user_authenticate.' + uid_input, true);
  return;
}




////////////////////////////////////////////////////////////////////////////////
//
// ユーザ登録フォームを生成
//
////////////////////////////////////////////////////////////////////////////////
function registrationForm() {
  var user_ = document.getElementById('user_');
  var user  = document.getElementById('user'); user.innerHTML = '';
  user.style.textAlign = 'right';

  var flg_submit = new Array();
  flg_submit['code'] = false;
  flg_submit['uid'] = false;
  flg_submit['uname'] = false;
  flg_submit['passwd'] = false;
  
  var submittable = function(elem, b) {
    flg_submit[elem] = b;
    var flg =   flg_submit['code']  &&  flg_submit['uid']  &&  flg_submit['uname']  &&  flg_submit['passwd'];
    document.getElementById('register_submit').disabled = !flg;
  }


  var h3 = document.createElement('h3');
  h3.style.textAlign = 'left';
  h3.innerHTML = 'ユーザの新規登録';
  user.appendChild(h3);
  
  var p_msg = document.createElement('p');
  p_msg.innerHTML = '以下の項目に入力後，“Register” ボタンを押してください．';
  user.appendChild(p_msg);
  //
  // Invitation Code 1, 2
  //
  var input_code1 = document.createElement('input'), input_code2 = document.createElement('input');
  input_code1.id = 'register_code1'; input_code2.id = 'register_code2';
  input_code1.type = input_code2.type = 'text';
  var note_code = document.createElement('p');
  note_code.className = 'note';
  note_code.innerHTML = 'メールに記載された招待コード （Invitation Code） を順に入力してください．';
  var checkInvitationCode = function(e) {
    if( input_code1.value.match(/^\s*$/)  &&  input_code2.value.match(/^\s*$/) ) {
      note_code.innerHTML = 'メールに記載された招待コード （Invitation Code） を順に入力してください．';
      submittable('code', false);
      return;
    }
    else if( !input_code1.value.match(/^\w{32}$/)  ||  !input_code2.value.match(/^\w{32}$/) ) {
      note_code.innerHTML = '招待コード （Invitation Code） に誤りがあります．';
      submittable('code', false);
      return;
    }
    
    var func = function(xml) {
      if( getNodeValue(xml, 'result', 0) == g_result_true ) {
        note_code.innerHTML = 'OK．';
        submittable('code', true);
      }
      else { // getNodeValue(xml, 'result', 0) == g_result_false
        note_code.innerHTML = '招待コード （Invitation Code） に誤りがあります．';
        submittable('code', false);
      }
      return;
    }
    var query = new Array();
    query.push('cmd=register_check_code');
    query.push('code1=' + input_code1.value);
    query.push('code2=' + input_code2.value);
    httpXMLRequest(dir('cgi', 0) + 'user.cgi', 'POST', array2queryString(query), func, httpError, 'cgi_user_register_checkInvitationCode', true);
    return;
  }
  addListener(input_code1, 'keyup', checkInvitationCode, false);
  addListener(input_code1, 'blur', checkInvitationCode, false);
  addListener(input_code2, 'keyup', checkInvitationCode, false);
  addListener(input_code2, 'blur', checkInvitationCode, false);
  user.appendChild(document.createTextNode('Invitation Code 1: '));
  user.appendChild(input_code1); user.appendChild(document.createElement('br'));
  user.appendChild(document.createTextNode('Invitation Code 2: '));
  user.appendChild(input_code2);
  user.appendChild(note_code);
  //
  // User ID
  //
  var input_uid = document.createElement('input');
  input_uid.id = 'register_uid';
  input_uid.type = 'text';
  var note_uid = document.createElement('p');
  note_uid.id = 'register_note_uid';
  note_uid.className = 'note';
  note_uid.innerHTML = '半角英数で入力してください．';
  var checkUID = function(e) {
    if( input_uid.value.match(/=|&|<|>/) ) {
      note_uid.innerHTML = '不正な文字が入っています．';
      submittable('uid', false);
      return;
    }
    if( input_uid.value.match(/^\s*$/) ) {
      note_uid.innerHTML = '半角英数で入力してください．';
      submittable('uid', false);
      return;
    }
    var func = function(xml) {
      if( getNodeValue(xml, 'result', 0) == g_result_true ) {
        note_uid.innerHTML = 'OK．';
        submittable('uid', true);
        if( document.getElementById('register_uname').value == '' ) { document.getElementById('register_uname').value = input_uid.value; }
      }
      else {
        note_uid.innerHTML = 'その ID はすでに存在します．';
        submittable('uid', false);
        input_uid.value = '';
        input_uid.focus();
      }
      return;
    }
    var query = new Array();
    query.push('cmd=register_check_uid');
    query.push('uid=' + hex_md5(input_uid.value));
    httpXMLRequest(dir('cgi', 0) + 'user.cgi', 'POST', array2queryString(query), func, httpError, 'cgi_user_register_checkUID', true);
  }
  addListener(input_uid, 'blur', checkUID, false);
  user.appendChild(document.createTextNode('User ID: '));
  user.appendChild(input_uid);
  user.appendChild(note_uid);
  //
  // User Name
  //
  var input_uname = document.createElement('input');
  input_uname.id = 'register_uname';
  input_uname.type = 'text';
  var note_uname = document.createElement('p');
  note_uname.id = 'register_note_uname';
  note_uname.className = 'note';
  note_uname.innerHTML = '当サイト上であなたの名前として用いられます．';
  var checkUName = function(e) {
    if( input_uname.value.match(/^\s*$/) ) {
      input_uname.value = input_uid.value;
    }
    else if( input_uname.value.match(/[\<\>]|\<.*\>/) ) {
      input_uname.value = input_uid.value;
      note_uname.innerHTML = '不正な文字が入っていたため，デフォルト値に戻しました．';
    }
    else {
      note_uname.innerHTML = 'OK．';
    }
    submittable('uname', true);
    return;
  }
  addListener(input_uname, 'blur', checkUName, false);
  user.appendChild(document.createTextNode('User Name: '));
  user.appendChild(input_uname);
  user.appendChild(note_uname);
  //
  // Password
  //
  var input_passwd1 = document.createElement('input'), input_passwd2 = document.createElement('input');
  input_passwd1.id = 'register_passwd1'; input_passwd1.type = 'password';
  input_passwd2.id = 'register_passwd2'; input_passwd2.type = 'password';
  var note_passwd = document.createElement('p');
  note_passwd.id = 'register_note_passwd';
  note_passwd.className = 'note';
  note_passwd.innerHTML = '同一のものを二度入力してください．';
  var checkPasswd = function() {
    var passwd1 = input_passwd1.value, passwd2 = input_passwd2.value;
    if( passwd1 == passwd2 ) {
      if( passwd1.match(/^\s*$/) ) {
        note_passwd.innerHTML = '同一のものを二度入力してください．';
        submittable('passwd', false);
        return;
      }
      else {
        note_passwd.innerHTML = 'OK．';
        submittable('passwd', true);
      }
    }        
    else {
      note_passwd.innerHTML = '一致していません．';
      submittable('passwd', false);
    }
    return;
  }
  addListener(input_passwd1, 'keyup', checkPasswd, false); addListener(input_passwd1, 'blur', checkPasswd, false);
  addListener(input_passwd2, 'keyup', checkPasswd, false); addListener(input_passwd2, 'blur', checkPasswd, false);
  user.appendChild(document.createTextNode('Password: '));
  user.appendChild(input_passwd1);
  user.appendChild(document.createElement('br'));
  user.appendChild(document.createTextNode('もう一度 Password: '));
  user.appendChild(input_passwd2);
  user.appendChild(note_passwd);
  //
  // ログインフォームに戻る
  //
  var p_login = document.createElement('p');
  p_login.style.margin = '6px 0 0 0';
  p_login.innerHTML = 'ログインフォームに戻る';
  addListener(p_login, 'click', loginForm, false);
  user.appendChild(p_login);

  //
  // Register ボタン
  //
  var div_register = document.createElement('div'); div_register.style.textAlign = 'right';
  var input_register = document.createElement('input');
  input_register.id = 'register_submit';
  input_register.className = 'btn';
  input_register.type = 'button';
  input_register.value = 'Register';
  input_register.title = 'このユーザを新規登録します．';
  input_register.disabled = true;
  addListener(input_register, 'click', createUser, false);
  user.appendChild(document.createElement('br'));
  user.appendChild(input_register);

  //
  // フッタ
  //
  var foot_user = document.createElement('div'); foot_user.id = 'foot_user';
  // 閉じるアイコン
  var img_close = document.createElement('img');
  img_close.id = 'user_profile_close';
  img_close.src = dir('img', 0) + 'common/icons/user_close.png';
  img_close.title = 'フォームを閉じます．';
  addListener(img_close, 'click', hideUserProfile, false);
  foot_user.appendChild(img_close);
  user.appendChild(foot_user);
  

  input_code1.focus();
  return;
}
////////////////////////////////////////////////////////////////////////////////
//
// 新規ユーザを作成する
//
////////////////////////////////////////////////////////////////////////////////
function createUser(e) {
  getTargetElement(e).disabled = true;
  var user = document.getElementById('user');

  var code1 = document.getElementById('register_code1').value;
  var code2 = document.getElementById('register_code2').value;
  var uid = hex_md5(document.getElementById('register_uid').value);
  var uname = document.getElementById('register_uname').value;
  var passwd = hex_md5(document.getElementById('register_passwd1').value);

  var func = function(xml) {
    user.uid = uid;
    user.uname = uname;
    var time = setCookie_login(true);
    var firstLogin = function(xml) {
      location.reload();
      return;
    }
    var query = new Array();
    query.push('cmd=login');
    query.push('uid=' + uid);
    query.push('time=' + time);
    httpXMLRequest(dir('cgi', 0) + 'user.cgi', 'POST', array2queryString(query), firstLogin, httpError, 'cgi_user_register_login.' + uid, true);
    return;
  }
  var query = new Array();
  query.push('cmd=register_user');
  query.push('code1=' + code1);
  query.push('code2=' + code2);
  query.push('uid=' + uid);
  query.push('uname=' + uname);
  query.push('passwd=' + passwd);
  httpXMLRequest(dir('cgi', 0) + 'user.cgi', 'POST', array2queryString(query), func, httpError, 'cgi_register_create.' + uid, true);
  return;
}




////////////////////////////////////////////////////////////////////////////////
//
// ログアウト
//
////////////////////////////////////////////////////////////////////////////////
function logout() {
  var user_ = document.getElementById('user_');
  var user  = document.getElementById('user');

  var func = function(xml) {
    setCookie_login(false);
    user.uname = g_uname_guest;
    location.reload();
    return;
  }
  var query = new Array();
  query.push('cmd=logout');
  query.push('uid=' + user.uid);
  httpXMLRequest(dir('cgi', 0) + 'user.cgi', 'POST', array2queryString(query), func, httpError, 'cgi_user_logout.' + user.uid, true);
  return;
}



////////////////////////////////////////////////////////////////////////////////
//
// Cookie
//
////////////////////////////////////////////////////////////////////////////////
//
// ログイン関連．時間（暗号化文字列）を返す
//
function setCookie_login(flg) {
  var uid = document.getElementById('user').uid;
  var date = new Date();
  var time = hex_md5(date.getTime().toString());
  flg
    ?  date.setTime(date.getTime() + g_milliseconds_expire)  // セット
    :  date.setYear(date.getYear() - 1); // 削除： 有効期限を過去の時間に
  document.cookie = 'uid=' + escape(uid) + '&time=' + escape(time) + '; expires=' + date.toGMTString() + '; ';
  return time;
}
//
// 現在のエリアマップ
//
function setCookie_areamap() {
  var areamap = document.getElementById('areamap');
  var select_w = areamap.getAttribute('select_world');
  var select_a = areamap.getAttribute('select_area');
  var select_m = areamap.getAttribute('select_map');
  //var date = new Date(); date.setTime(date.getTime() + g_milliseconds_expire);
  var date = new Date(); date.setTime(date.getTime() + 1000 * 60 * 60 * 24 * 7);
  document.cookie = 'w=' + select_w + '&a=' + select_a + '&m=' + select_m + '; expires=' + date.toGMTString() + '; ';
  return;
}

